js比较两个单独的数组或对象是否相等
所谓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 method
if(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 array
Array.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 loops
Object.defineProperty(Array.prototype, "equals", {enumerable: false});
2.比较对象
Object.prototype.equals = function(object2) {
//For the first loop, we only check for types
for (propName in this) {
//Check for inherited methods and properties - like .equals itself
//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
//Return false if the return value is different
if (this.hasOwnProperty(propName) != object2.hasOwnProperty(propName)) {
return false;
}
//Check instance type
else if (typeof this[propName] != typeof object2[propName]) {
//Different types => not equal
return false;
}
}
//Now a deeper check using other objects property names
for(propName in object2) {
//We must check instances anyway, there may be a property that only exists in object2
//I wonder, if remembering the checked values from the first loop would be faster or not
if (this.hasOwnProperty(propName) != object2.hasOwnProperty(propName)) {
return false;
}
else if (typeof this[propName] != typeof object2[propName]) {
return false;
}
//If the property is inherited, do not check any more (it must be equa if both objects inherit it)
if(!this.hasOwnProperty(propName))
continue;
//Now the detail check and recursion
//This returns the script back to the array comparing
/**REQUIRES Array.equals**/
if (this[propName] instanceof Array && object2[propName] instanceof Array) {
// recurse into the nested arrays
if (!this[propName].equals(object2[propName]))
return false;
}
else if (this[propName] instanceof Object && object2[propName] instanceof Object) {
// recurse into another objects
//console.log("Recursing to compare ", this[propName],"with",object2[propName], " both named \""+propName+"\"");
if (!this[propName].equals(object2[propName]))
return false;
}
//Normal value comparison for strings and numbers
else if(this[propName] != object2[propName]) {
return false;
}
}
//If everything passed, let's say YES
return true;
}
js比较两个单独的数组或对象是否相等的更多相关文章
- 精读JavaScript模式(四),数组,对象与函数的几种创建方式
一.前言 放了个元旦,休息了三天,加上春运抢票一系列事情的冲击,我感觉我的心已经飞了.确实应该收收心,之前计划的学习任务也严重脱节了:我恨不得打死我自己. 在上篇博客中,笔记记录到了关于构造函数方面的 ...
- JS合并两个数组的方法
JS合并两个数组的方法 我们在项目过程中,有时候会遇到需要将两个数组合并成为一个的情况.比如: var a = [1,2,3]; var b = [4,5,6]; 有两个数组a.b,需求是将两个数组合 ...
- JS取出两个数组的不同或相同元素
JS合并两个数组的方法 我们在项目过程中,有时候会遇到需要将两个数组合并成为一个的情况.比如: var a = [1,2,3]; var b = [4,5,6]; 有两个数组a.b,需求是将两个数组合 ...
- JS中实现数组和对象的深拷贝和浅拷贝
数组的拷贝 > 数组的深拷贝,两层 var arr = [[1,2,3],[4,5,6],[7,8,9]]; var arr2 = []; 循环第一层数组 for(var i=0,len=arr ...
- js中两个对象的比较
代码取自于underscore.js 1.8.3的isEqual函数. 做了一些小小的修改,主要是Function的比较修改. 自己也加了一些代码解读. <!DOCTYPE html> & ...
- JS 学习笔记--5---对象和数组
1.Object类型(引用类型) 不具备多少功能,但是对于在ECMAScript中存储和传递数据确实,确是很理想的选择. 创建方式:(1).使用new Object();方式创建对象,然后对对象进行设 ...
- js判断一个变量是否为数组的解决方案
前端开发中,在做项目的时候,我们经常需要对一个变量进行数组类型的判断,当然即使你暂时没遇到,但是这个问题也是大家去面试时的高频问题,有必要拿出来说一说. 大家都知道js中可以使用typeof来判断变量 ...
- JS分两种数据类型,你都知道吗?
大牛请无视此篇! JS主要分基本数据类型和引用数据类型,这两者区别可大了,此篇看完必有长进,下面进入正题 首先我们看下什么是基本数据类型(概念我就不说了,直接上代码): var i = 10: var ...
- 用js来实现那些数据结构(数组篇01)
在开始正式的内容之前,不得不说说js中的数据类型和数据结构,以及一些比较容易让人混淆的概念.那么为什么要从数组说起?数组在js中是最常见的内存数据结构,数组数据结构在js中拥有很多的方法,很多初学者记 ...
随机推荐
- appium自动化测试等待的三种方法
第一种 sleep(): 设置固定休眠时间.python 的 time 包提供了休眠方法 sleep() ,导入 time包后就可以使用 sleep()进行脚本的执行过程进行休眠. python # ...
- dynamic不能使用扩展方法
一.方法中传入的参数为dynamic,则返回的也是dynamic类型 例如: public string Test(string str) { return str + "aa"; ...
- Wine中中文显示为错误的解决方案
First u must download wqy-microhei.ttc font online (https://github.com/anthonyfok/fonts-wqy-microhei ...
- scrapy相关:splash安装 A javascript rendering service 渲染
0. splash: 美人鱼 溅,泼 1.参考 Splash使用初体验 docker在windows下的安装 https://blog.scrapinghub.com/2015/03/02/hand ...
- java 安装以及配置
1.下载 JDK 下载地址:https://www.oracle.com/technetwork/java/javase/downloads/index-jsp-138363.html 2.环境变量配 ...
- Pop Star 1.2.5
原文链接https://www.cnblogs.com/zhouzhendong/p/Pop-Star.html 是VB写的. 年代久远,代码太丑,原码不公开. 下载链接 仅支持Windows,需要解 ...
- java代码获取多边形的中心点
package com.skjd.util; import java.util.ArrayList; import java.util.List; /** * 坐标以及电子围栏相关的工具类 * @au ...
- url 中文及特殊字符转码
#include <ctype.h> std::string UrlEncode(const std::string& szToEncode) { std::string s ...
- Node.js_express_route 路由
route 路由 (kiss my ass ヾ(゚∀゚ゞ) 请求方式 get / post / put / delete____查 / 增 / 改 / 删 路由路径 ...
- swust oj 971
统计利用先序遍历创建的二叉树的深度 10000(ms) 10000(kb) 3331 / 8436 利用先序递归遍历算法创建二叉树并计算该二叉树的深度.先序递归遍历建立二叉树的方法为:按照先序递归遍历 ...