所谓js的中的传值,其实也就是说5种基本数据类型(null,undefind,boolean,number,string)
传引用也就是说的那个引用数据类型,(array和object)
基本数据类型的值不可变,而引用数据类型的值是可变的
所以当你比较数组和对象时,都是false;除非你是克隆的原份数据
即: var a = { name: "李四" }; var b = a;
大家通常称对象为引用类型,以此来和基本类型进行区分; 而对象值都是引用,所以的对象的比较也叫引用的比较,当且当他们都指向同一个引用时,即都引用的同一个基对象时,它们才相等.
1.比较两个单独的数组是否相等
JSON.stringify(a1) == JSON.stringify(a2)
或
a1.toString() == a2.toString()
要判断2个数组是否相同,把数组转换成字符串进行比较。
如果要比较两个数组的元素是否相等,则:
JSON.stringify([1,2,3].sort()) === JSON.stringify([3,2,1].sort());
或
[1,2,3].sort().toString() === [3,2,1].sort().toString();
判断2个数组是否相同,首先要把数组进行排序,然后转换成字符串进行比较。
2.比较两个单独的对象是否相等
let cmp = ( x, y ) => {// If both x and y are null or undefined and exactly the same if ( x === y ) { return true; }// If they are not strictly equal, they both need to be Objects if ( ! ( x instanceof Object ) || ! ( y instanceof Object ) ) { return false; }//They must have the exact same prototype chain,the closest we can do is//test the constructor. if ( x.constructor !== y.constructor ) { return false; } for ( var p in x ) { //Inherited properties were tested using x.constructor === y.constructor if ( x.hasOwnProperty( p ) ) { // Allows comparing x[ p ] and y[ p ] when set to undefined if ( ! y.hasOwnProperty( p ) ) { return false; } // If they have the same strict value or identity then they are equal if ( x[ p ] === y[ p ] ) { continue; } // Numbers, Strings, Functions, Booleans must be strictly equal if ( typeof( x[ p ] ) !== "object" ) { return false; } // Objects and Arrays must be tested recursively if ( ! Object.equals( x[ p ], y[ p ] ) ) { return false; } } } for ( p in y ) { // allows x[ p ] to be set to undefined if ( y.hasOwnProperty( p ) && ! x.hasOwnProperty( p ) ) { return false; } } return true;};
下面是StackOverflow大神封装的方法,可以学习一下:
1.比较数组
// Warn if overriding existing methodif(Array.prototype.equals) console.warn("Overriding existing Array.prototype.equals. Possible causes: New API defines the method, there's a framework conflict or you've got double inclusions in your code.");// attach the .equals method to Array's prototype to call it on any arrayArray.prototype.equals = function (array) { // if the other array is a falsy value, return if (!array) return false; // compare lengths - can save a lot of time if (this.length != array.length) return false; for (var i = 0, l = this.length; i < l; i++) { // Check if we have nested arrays if (this[i] instanceof Array && array[i] instanceof Array) { // recurse into the nested arrays if (!this[i].equals(array[i])) return false; } else if (this[i] != array[i]) { // Warning - two different object instances will never be equal: {x:20} != {x:20} return false; } } return true;}// Hide method from for-in loopsObject.defineProperty(Array.prototype, "equals", {enumerable: false});
新闻热点
疑难解答
图片精选