javascript 在javascript中检查数组是否包含null以外的内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34031690/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if an array contains something other than null in javascript?
提问by mre12345
I have an array that will most likely always look like:
我有一个很可能总是看起来像的数组:
[null, null, null, null, null]
sometimes this array might change to something like:
有时这个数组可能会变成类似的东西:
["helloworld", null, null, null, null]
I know I could use a for loop for this but is there a way to use indexOfto check if something in an array that is not equal to null.
我知道我可以为此使用 for 循环,但是有没有一种方法可以indexOf用来检查数组中的某些内容是否不等于 null。
I am looking for something like:
我正在寻找类似的东西:
var index = indexof(!null);
回答by Andy
回答by Paul Roub
In recent versions of Chrome, Safari, and Firefox (and future versions of other browsers), you can use findIndex()to find the index of the first non-null element.
在 Chrome、Safari 和 Firefox(以及其他浏览器的未来版本)的最新版本中,您可以使用findIndex()来查找第一个非空元素的索引。
var arr = [null, null, "not null", null];
var first = arr.findIndex(
function(el) {
return (el !== null);
}
);
console.log(first);
(for other browsers, there's a polyfill for findIndex())
(对于其他浏览器,有一个polyfill forfindIndex())
回答by TbWill4321
You can use Array.prototype.someto check if there are any elements matching a function:
您可以使用Array.prototype.some来检查是否有任何元素与函数匹配:
var array = [null, null, 2, null];
var hasValue = array.some(function(value) {
return value !== null;
});
document.write('Has Value? ' + hasValue);
If you want the first index of a non-null element, you'll have to get a bit trickier. First, map each element to true / false, then get the indexOf true:
如果你想要一个非空元素的第一个索引,你将不得不变得有点棘手。首先,将每个元素映射到true/false,然后获取indexOf true:
var array = [null, null, 2, null, 3];
var index = array
.map(function(value) { return value !== null })
.indexOf(true);
document.write('Non-Null Index Is: ' + index);
回答by Tobias Feil
回答by Shakawkaw
This does the work
这做的工作
var array = ['hello',null,null];
var array2 = [null,null,null];
$.each(array, function(i, v){
if(!(v == null)) alert('Contains data');
})

