3

js判断两个数组相等的方法

 2 years ago
source link: https://xushanxiang.com/check-if-arrays-are-equal.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

js判断两个数组相等的方法

作者: xusx 分类: JavaScript 发布时间: 2022-05-01 10:16 浏览:15

在 js 中是不能直接用 == 或者 === 来比较两个数组是否相等,那就需要对数组的值进行比较。

下面各种方法,要根据具体情况来使用。

一、 toString()

当两个数组元素类型相同,顺序相同时,直接判断是否相等,结果不相等;转化为字符串后,结果相等

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

二、join()

[1,2,3,'4'].join() === [1,2,3, 4].join(); // true

三、 JSON.stringify()

JSON.stringify([{name:'许善祥'},{sex:'男'}]) == JSON.stringify([{name:'许善祥'},{sex:'男'}]); // true

四、sort()

当两个数组元素排序不相同时,先排序,再比较。如果是对象数组,可以结合 JSON.stringify 来使用。

var a = ['1', '3', '2'];
var b = ['3', '1', '2'];

var c = a.length === b.length && a.sort().toString() === b.sort().toString();

console.log(c); // true
JavaScript

五、filter()

var a = ['1', '3', '2'];
var b = ['3', '1', '2'];

var c = a.length === b.length && a.filter(t => !b.includes(t));

console.log(c); // true
JavaScript

filter() 创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
语法:
array.filter(function(currentValue,index,arr), thisValue);

相关文章:js判断两个对象相等的方法

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK