在 JavaScript 中检查“未定义”上的数组项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9344343/
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
Checking item of array on "undefined" in JavaScript
提问by Eugene Shmorgun
My JS-code has array arrayResults, some element of him can be "undefined" - this is feature of algorithm. To check that there is no such elements I use the follow code:
我的 JS 代码有数组arrayResults,他的某些元素可以是“未定义的” - 这是算法的特征。要检查是否没有这样的元素,我使用以下代码:
for (i in arrayResults)
{
if (typeof(arrayResults[i])=='undefined')
{
// ask user to repeat
};
};
But, using the debugger, I found that JS-engine passes the "undefined"-item of array (in for condition), respectively I don't have the possibility to make the comparing and make the follow instructions.
但是,使用调试器,我发现 JS 引擎传递了数组的“未定义”项(在 for 条件中),分别我无法进行比较并进行以下说明。
So, is there any way to really check the "undefined" items in array? (I can't to set items of array in sequence, because if I found the position of "undefined" item, I tell to user to go to this position).
那么,有没有办法真正检查数组中的“未定义”项?(我不能按顺序设置数组的项目,因为如果我找到“未定义”项目的位置,我会告诉用户去这个位置)。
回答by kapa
Don't use a for..in
loop to iterate arrays. If you are interested in the reasons, please read this StackOverflow question. They should only be used for traversing objects.
不要使用for..in
循环来迭代数组。如果您对原因感兴趣,请阅读此 StackOverflow 问题。它们应该只用于遍历对象。
Use a simple oldschool for
loop instead, it will solve your problem.
改用一个简单的 oldschoolfor
循环,它将解决您的问题。
for (var i = 0, l = arrayResults.length; i < l; i++) {
if (typeof(arrayResults[i])=='undefined') {
// ask user to repeat
};
};
回答by Mateusz Nowak
You can use indexOf
method on array.
您可以indexOf
在数组上使用方法。
function hasUndefined(a) {
return a.indexOf() !== -1;
}
hasUndefined([1,2,3, undefined, 5]);