这将用于测试一个值在位置索引是否存在,或者有更好的方法:
if(arrayName[index]==""){
// do stuff
}
这将用于测试一个值在位置索引是否存在,或者有更好的方法:
if(arrayName[index]==""){
// do stuff
}
当前回答
检查它是否从未被定义或是否被删除:
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(typeof arr ==='object' && arr instanceof Array ){
if(!arr.length){
println 'empty'
}else{
printn 'not Empty'
}
}else{
println 'Null'
}
如果你的意思是'Null' ->它的元素为Null或等于",在这种情况下:在过滤所有'Null'元素后检查数组是否为空
if(!arr.clean().length){return 'is null'}
当然,之前的Add Clean方法:
Array.prototype.clean=function(){return this.filter(function(e){return (typeof e !=='undefined')&&(e!= null)&&(e!='')})}
我想指出一些似乎已经错过的东西:即有可能在数组的中间有一个“空”数组位置。考虑以下几点:
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(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
}
好的,让我们先看看如果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 南:不是数字 假
实检测:在运算符中
这个问题的年龄大约是10年,令人惊讶的是,还没有人提到这一点-然而,有些人看到了当我们使用删除操作符(例如这里)时的问题。这也是一个有点违反直觉的解决方案,但在“对象世界”中工作的in操作符也可以用于数组(因为我们可以像在“键”上一样查看数组索引……)通过这种方式,我们可以检测并区分未定义的数组值和被delete删除的值(索引)
if(index in arrayName) {
// do stuff
}
let arr = [0, 1, 2, 3, null, undefined,6] delete arr[2]; // we delete element at index=2 if(2 in arr) console.log('You will not see this because idx 2 was deleted'); if(5 in arr) console.log('This is element arr[5]:', arr[5]); // Whole array and indexes bigger than arr.length: for(let i=0; i<=9; i++) { let val = (i in arr) ? arr[i] : 'empty' let bound = i<arr.length ? '' : '(out of range)' console.log(`${i} value: `, val, bound); } console.log('Look on below aray on chrome console (not in SO snippet console)'); console.log('typeof arr:', typeof arr); console.log(arr);
Chrome控制台显示了一些关于删除索引2的代码片段数组的信息-这个索引实际上根本不存在(!!)(就像从对象中删除键一样)。有趣的是,数组被视为键值对(我们甚至看到'length'键)。同样有趣的是,typeof arr是Object (!!), delete和in操作符的工作方式类似于JS对象 (同样方括号符号arr[idx]和obj[key]是类似的)-所以它看起来像数组是一些特殊的JS对象在核心。
为了得到类似的效果而不删除定义数组如下
[0, 1,, 3, null, undefined, 6] // pay attention to double comma: ",,"