这将用于测试一个值在位置索引是否存在,或者有更好的方法:
if(arrayName[index]==""){
// do stuff
}
这将用于测试一个值在位置索引是否存在,或者有更好的方法:
if(arrayName[index]==""){
// do stuff
}
当前回答
实检测:在运算符中
这个问题的年龄大约是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: ",,"
其他回答
如果数组[index]为空,请尝试此操作
if (array[index] != null)
我在使用laravel数据表时遇到了这个问题。我在活动日志中存储了一个名为properties的JSON值,并希望根据该值是否为空来显示一个按钮。
好吧,数据表是解释这作为一个数组,如果它是空的,和一个对象,如果它不是,因此,下面的解决方案为我工作:
render: function (data, type, full) {
if (full.properties.length !== 0) {
// 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(!arrayName[index]){
// do stuff
}
if(arrayName.length > index && arrayName[index] !== null) {
//arrayName[index] has a value
}