Browsing vuejs source code in leisure boredom, found a relatively strong contrast method even array objects can be compared correctly; There is also a strong indexOf which can be used to determine whether a value is present in the data. If it is useful to you, please like it and share it. Without further ado, go directly to the code:
/** * check whether it is the base type object@param {any} Obj passes in the data type * to be judged@returns True for object, false */ otherwise
function isObject (obj) {
returnobj ! = =null && typeof obj === 'object'
}
/** * determines whether two values are equal *@param {any} A Any data type *@param {any} B Any data type *@returns True: consistent; false: unequal */
function looseEqual (a, b) {
if (a === b) { return true }
var isObjectA = isObject(a);
var isObjectB = isObject(b);
if (isObjectA && isObjectB) {
try {
var isArrayA = Array.isArray(a);
var isArrayB = Array.isArray(b);
if (isArrayA && isArrayB) {
return a.length === b.length && a.every(function (e, i) {
return looseEqual(e, b[i])
})
} else if (a instanceof Date && b instanceof Date) {
return a.getTime() === b.getTime()
} else if(! isArrayA && ! isArrayB) {var keysA = Object.keys(a);
var keysB = Object.keys(b);
return keysA.length === keysB.length && keysA.every(function (key) {
return looseEqual(a[key], b[key])
})
} else {
/* istanbul ignore next */
return false}}catch (e) {
/* istanbul ignore next */
return false}}else if(! isObjectA && ! isObjectB) {return String(a) === String(b)
} else {
return false}}/** * gets the position of the current value * in the collection@param {any} Arr incoming collection *@param {any} Val queries whether the value * is located in the collection@returns -1 indicates that it does not exist, and 0 or above indicates that the subscript */ exists
function looseIndexOf (arr, val) {
for (var i = 0; i < arr.length; i++) {
if (looseEqual(arr[i], val)) { return i }
}
return -1
}
Copy the code
Pro test is valid, if you have any questions, please leave a message. (The author is lazy to carry directly, so it is not changed to ES6. If necessary, it will be changed by itself.)