_.each 在数组 return 中查找值是对还是错。使用下划线 js

_.each find value in array return true or false. using underscore js

//使用 underscoreJS _.each 使用函数 checkValue 在数组中查找值。 //return 为真,否则为假。

var helloArr = ['bonjour', 'hello', 'hola'];

var checkValue = function(arg) {
    _.each(helloArr, function(helloArr, index) {
        if (arg[index] === index) {
            return true;
        }
        return false;
    });
};
alert(checkValue("hola"));

您的代码问题 是,_.each 将遍历数组的所有元素并调用您传递给它的函数。您将无法得出结论,因为您没有从中获得任何返回值(除非您在 _.each 之外维护状态)。

请注意,您传递给 _.each 的函数返回的值不会在任何地方使用,它们不会以任何方式影响程序的进程。

但是,您可以使用 _.some 作为 替代方法 ,像这样

var checkValue = function(arg) {
    return _.some(helloArr, function(currentString) {
        return arg === currentString;
    });
};

但是,更好的解决方案_.contains 用于此目的的函数。你可以这样使用它

var checkValue = function(arg) {
    return _.contains(helloArr, arg);
};

但是,由于数组中只有字符串,最好的解决方案 是使用 Array.prototype.indexOf,像这样

var checkValue = function(arg) {
    return helloArr.indexOf(arg) !== -1;
};

试试这个:

var helloArr = ['bonjour', 'hello', 'hola'];

var checkValue = function(arr, val) {
  _(arr).each(function(value) {

         if (value == val)
           {return console.log(true);}
       else {return console.log(false);}
  });
};

console.log(checkValue(helloArr,'hello'));

/* Output 
false
true
false*/