视频1 视频21 视频41 视频61 视频文章1 视频文章21 视频文章41 视频文章61 推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37 推荐39 推荐41 推荐43 推荐45 推荐47 推荐49 关键词1 关键词101 关键词201 关键词301 关键词401 关键词501 关键词601 关键词701 关键词801 关键词901 关键词1001 关键词1101 关键词1201 关键词1301 关键词1401 关键词1501 关键词1601 关键词1701 关键词1801 关键词1901 视频扩展1 视频扩展6 视频扩展11 视频扩展16 文章1 文章201 文章401 文章601 文章801 文章1001 资讯1 资讯501 资讯1001 资讯1501 标签1 标签501 标签1001 关键词1 关键词501 关键词1001 关键词1501 专题2001
JS判断两个数组或对象是否相同的方法示例
2020-11-27 22:00:31 责编:小采
文档


本文实例讲述了JS判断两个数组或对象是否相同的方法。分享给大家供大家参考,具体如下:

JS 判断两个数组是否相同

要判断2个数组是否相同,首先要把数组进行排序,然后转换成字符串进行比较。

JSON.stringify([1,2,3].sort()) === JSON.stringify([3,2,1].sort()); //true

或者

[1,2,3].sort().toString() === [3,2,1].sort().toString(); //true

经验证,上述方法对复杂数组结构不适用。

JS 判断两个对象是否相同

这是网上某大神封装对比对象是否相同的 function。

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;
};

经检测,同样也不支持复杂数据结构的对象。

一般情况下用的话上述2种方法已经够用了,拿来作比较的一般都是简单的数据结构。

更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《JavaScript数组操作技巧总结》、《JavaScript遍历算法与技巧总结》、《javascript面向对象入门教程》、《JavaScript数算用法总结》、《JavaScript数据结构与算法技巧总结》及《JavaScript错误与调试技巧总结》

希望本文所述对大家JavaScript程序设计有所帮助。

下载本文
显示全文
专题