Javascript问题。
正如标题所述,是否可以将布尔值(true或false)设置为数组,然后检查数组中是否存在这些值之一?
假设我有返回true或false的函数。
示例代码:(使用jQuery)
var abort = [];//make an empty array
function someFunc() {
var returnVal = false;
if( some condition ) {
returnVal = true;
return returnVal;
}
return returnVal;
}
someElement.each(function() {
abort.push( someFunc() ); //push true or false in array
});
//abort array will look eventually something like...
//[true, false, true, false, false, true, ...]
//check if `true` exists in array jQuery approach
var stop = ( $.inArray(true, abort) > -1) ? true : false ;
if( stop ) {
console.log('TRUE FOUND AT LEAST ONE IN ARRAY!');
}这似乎没问题。但我只是想知道这是不是正确的方法..。
发布于 2014-01-23 08:05:09
如果不想调用所有函数,如果其中任何函数返回true,则可以使用以下的本机Array.prototype.some方法
if (someElement.some(function(currentObject) {
return <a bool value>;
}))) {
console.log("Value exists");
} else {
console.loe("Value doesn't exist");
}例如,
var someArray = [1,5,6,8,3,8];
if(someArray.some(function(currentObject) {
return currentObject === 3;
})) {
console.log("3 exists in the array");
} else {
console.log("3 does not exist in the array");
}会打印
3 exists in the array如果您想执行所有函数,而不管结果如何,但是如果您想知道其中至少一个函数是否返回了true,那么您可以使用Array.prototype.reduce,如下所示
var someArray = [1,5,6,8,4,8];
function printer(currentObject) {
console.log(currentObject);
return currentObject === 3;
}
if(someArray.reduce(function(result, currentObject) {
return result || printer(currentObject);
}, false)) {
console.log("3 exists in the array");
} else {
console.log("3 does not exist in the array");
}输出
1
5
6
8
4
8
3 does not exist in the arrayhttps://stackoverflow.com/questions/21302521
复制相似问题