这将用于测试一个值在位置索引是否存在,或者有更好的方法:
if(arrayName[index]==""){
// do stuff
}
这将用于测试一个值在位置索引是否存在,或者有更好的方法:
if(arrayName[index]==""){
// do stuff
}
当前回答
当你创建的空数组值不是undefined时,它们是empty
var arr = new Array(10); // (10) [empty × 10]
但是当你通过索引获取item时,receive undefined
arr[0]; // undefined
所以你不能通过===比较知道它们是未定义的还是空的
我们可以使用JSON。Stringify,转换整个数组,将空值替换为null
JSON.stringify(arr); // "[null,null,null,null,null,null,null,null,null,null]"
JSON.stringify(arr[0]); // but for single item it returns undefined
对空值的实检查:
arr[0] !== null && JSON.stringify(arr.map(item => !item)).slice(1, -1).split(',')[0] === 'null'
将item与null进行比较(不应等于) 映射数组删除false代替现有值(确保字符串结构用逗号分隔,没有多余的逗号) JSON。stringify数组 从字符串中移除括号 用逗号分割成数组 与null比较
其他回答
检查它是否从未被定义或是否被删除:
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
}
if(arrayName.length > index && arrayName[index] !== null) {
//arrayName[index] has a value
}
你可以使用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/
我认为这个决定适合那些喜欢声明式函数编程而不是命令式OOP或过程式编程的人。如果你的问题是“里面有价值吗?”(一个真实或虚假的值)”你可以使用。some方法来验证里面的值。
[].some(el => el || !el);
它并不完美,但它不需要应用任何包含相同逻辑的额外函数,如function isEmpty(arr){…}。 当我们这样做[]时,它听起来仍然比“它是零长度吗?”要好。长度导致0,在某些情况下是危险的。 甚至是这个[]。length > 0表示它的长度是否大于0 ?
先进的例子:
[ ].some(el => el || !el); // false
[null].some(el => el || !el); // true
[1, 3].some(el => el || !el); // true
我想指出一些似乎已经错过的东西:即有可能在数组的中间有一个“空”数组位置。考虑以下几点:
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
}