这将用于测试一个值在位置索引是否存在,或者有更好的方法:
if(arrayName[index]==""){
// do stuff
}
这将用于测试一个值在位置索引是否存在,或者有更好的方法:
if(arrayName[index]==""){
// do stuff
}
当前回答
好的,让我们先看看如果JavaScript中不存在数组值会发生什么,所以如果我们有一个如下所示的数组:
const arr = [1, 2, 3, 4, 5];
现在我们检查6是否在下标5处:
arr[5];
我们得到 未定义……
这基本上给了我们答案,检查是否未定义的最好方法,像这样:
if("undefined" === typeof arrayName[index]) {
//array value is not there...
}
在这种情况下最好不要这样做:
if(!arrayName[index]) {
//Don't check like this..
}
因为假设我们有这样一个数组:
const arr = [0, 1, 2];
我们这样做:
if(!arr[0]) {
//This get passed, because in JavaScript 0 is falsy
}
正如你所看到的,即使0在那里,它也不会被识别,还有一些其他的事情可以做同样的事情,让你的应用程序有bug,所以要小心,我把它们都列了下来:
Undefined:如果该值没有定义并且是未定义的 null:如果它是空的,例如如果一个DOM元素不存在… 空字符串:" 0:数字0 南:不是数字 假
其他回答
我想指出一些似乎已经错过的东西:即有可能在数组的中间有一个“空”数组位置。考虑以下几点:
let arr = [0, 1, 2, 3, 4, 5]
delete arr[3]
console.log(arr) // [0, 1, 2, empty, 4, 5]
console.log(arr[3]) // undefined
自然的检查方法是查看数组成员是否未定义,我不确定是否存在其他方法
if (arr[index] === undefined) {
// member does not exist
}
if(arrayName.length > index && arrayName[index] !== null) {
//arrayName[index] has a value
}
使用Lodash,你可以做到:
if(_.has(req,'documents')){
if (req.documents.length)
_.forEach(req.documents, function(document){
records.push(document);
});
} else {
}
if(_.has(req,'documents'))是检查我们的请求对象是否有一个名为documents的属性,如果它有prop,下一个if(req.documents.length)是验证它是否不是一个空数组,这样其他的东西,如forEach可以继续。
你可以使用Loadsh库来更有效地做到这一点,比如:
如果你有一个名为“pets”的数组,例如:
var pets = ['dog', undefined, 'cat', null];
console.log(_.isEmpty(pets[1])); // true
console.log(_.isEmpty(pets[3])); // true
console.log(_.isEmpty(pets[4])); // false
_.map( pets, (pet, index) => { console.log(index + ': ' + _.isEmpty(pet) ) });
检查所有数组值是否为空或未定义的值:
Var pets = ['dog', undefined, 'cat', null]; 宠物console.log (_.isEmpty ([1]));/ /正确的 console.log (_.isEmpty(宠物[3]));/ /正确的 console.log (_.isEmpty(宠物[4]));/ /错误 _。地图(宠物,宠物,指数= > {console.log(指数 + ': ' + _. isEmpty (pet))}); < script src = " https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js " > < /脚本>
更多例子请访问http://underscorejs.org/
检查它是否从未被定义或是否被删除:
if(typeof arrayName[index]==="undefined"){
//the index is not in the array
}
也适用于关联数组和删除某些索引的数组
要检查它是否从未被定义,was deleted OR是一个空值或逻辑空值(NaN,空字符串,false):
if(typeof arrayName[index]==="undefined"||arrayName[index]){
//the index is not defined or the value an empty value
}