javascript - 使用 .some() 比较数组

标签 javascript arrays

所以我尝试比较两个数组,看看它们的内容是否相同,请参见下面的示例

var array1 = [0,2,2,2,1]
var array2 = [0,2,2,2,3]

我想使用 some 方法比较这两个数组 所以我将编写一个函数,如果某些数字同时存在于两个数组中,则该函数返回 true。

我已经在一个数组上完美地使用了该方法,试图找到一个特定的值

function testArray(){
 var bool = array1.some(function(value){
   return value ===1;
 });
}
console.log(bool)

但是如何将它用于 2 个数组呢?感谢任何帮助

最佳答案

解决方案 Array.prototype.every()

The every() method tests whether all elements in the array pass the test implemented by the provided function.

Array.prototype.some()

The some() method tests whether some element in the array passes the test implemented by the provided function.

对于相同的任务。请注意刘海!

var array1 = [0, 2, 2, 2, 1],
    array2 = [0, 2, 2, 2, 3];

function compareEvery(a1, a2) {
    if (a1.length !== a2.length) { return false; }
    return a1.every(function (a, i) {
        return a === a2[i];
    });
}

function compareSome(a1, a2) {
    if (a1.length !== a2.length) { return false; }
    return !a1.some(function (a, i) {
        return a !== a2[i];
    });
}

document.write(compareEvery(array1, array2) + '<br>');
document.write(compareEvery(array1, array1) + '<br>');

document.write(compareSome(array1, array2) + '<br>');
document.write(compareSome(array1, array1) + '<br>');

关于javascript - 使用 .some() 比较数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35056086/

相关文章:

javascript - 检查页面加载时的 Facebook 登录状态

javascript - jQuery 选择全部而不是某些字段

javascript - 为什么我的 javascript 联系表单不起作用?

javascript - onLoad 返回 0 作为宽度和高度

javascript - 当存在超过 9 个相同脚本时,由于脚本原因,页面加载需要时间

javascript - 将两个不同的字符串拆分成一个数组?

java - 如何使用类方法计算数组中所有值的平均值

arrays - 如何在二维数组中找到总和最大的元素?

javascript - 从javascript数组获取随机值并将其打印为字符串

c - 如何在 ANSI C 程序中返回字符串数组?