使用map来检查是否为真'不起作用

using map to check for true or false doesn't work

本文关键字:不起作用 map 检查 是否 使用      更新时间:2023-09-26

在练习映射、过滤器等时,我尝试不使用循环,并想知道为什么我的代码不起作用?

function checking(array,item){
 var temporary=true;
array.map(function(x){
if (x!=item){
    temporary=false;
}
});
return temporary;
}
checking([1, 2, 3], 2);

为什么不使用Array#some,它非常适合检查和返回布尔值。如果回调返回为true,则最好是短路。

function checking(array, item) {		
    return array.some(function (x) {
        return x === item;
    });
}
document.write(checking([1, 2, 3], 2));

因为您不是在检查2是否在数组中,而是在检查数组是否具有与2不同的值。

你应该检查一下是否有。例如:

let temporary=false;
array.map(function(x){
if (x==item){
    temporary=true;
}