这个代码可以用来测试位置为index
的值是否存在,或者有更好的方法吗:
if(arrayName[index]==""){
// do stuff
}
这个代码可以用来测试位置为index
的值是否存在,或者有更好的方法吗:
if(arrayName[index]==""){
// do stuff
}
in
运算符这个问题已经存在了大约10年,令人惊讶的是,到目前为止没有人提到过 - 然而一些人在使用delete
运算符时(例如这里),会发现这个问题。这也是一个有点反直觉的解决方案,但是在“对象世界”中工作的in
运算符也可以与数组一起使用(因为我们可以像处理“键”一样来处理数组索引)。通过这种方式,我们可以检测和区分undefined
数组值和被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);
typeof arr
是Object (!!!),delete
和in
运算符的工作方式类似于JS对象(方括号表示法arr[idx]
和obj[key]
也很相似) - 这样看来数组是JS核心中的一些特殊JS对象。
要获得类似的效果而不使用delete
,请按以下方式定义数组:
[0, 1,, 3, null, undefined, 6] // pay attention to double comma: ",,"
好的,让我们首先看一下在JavaScript中如果一个数组值不存在会发生什么情况,所以如果我们有一个如下的数组:
const arr = [1, 2, 3, 4, 5];
arr[5];
我们得到了undefined
...
这基本上给出了答案,最好的方法是检查是否未定义,就像这样:
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
}
undefined
''
检查变量是否未定义或已被删除:
if(typeof arrayName[index]==="undefined"){
//the index is not in the array
}
也适用于关联数组和删除了某些索引的数组
要检查它是否从未被定义、已被删除或者是 null 或逻辑空值(NaN、空字符串、false):
if(typeof arrayName[index]==="undefined"||arrayName[index]){
//the index is not defined or the value an empty value
}
properties
的JSON值,并希望根据该值是否为空来显示一个按钮。render: function (data, type, full) {
if (full.properties.length !== 0) {
// do stuff
}
}
对象没有长度属性。
当你创建空数组时,值不是undefined,而是空的
var arr = new Array(10); // (10) [empty × 10]
但是当您通过索引获取项时,会收到未定义的值
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'
false
而不是现有值(确保字符串结构为逗号分隔,没有冗余逗号)null
进行比较我认为这个决定适合那些喜欢声明式函数式编程而非命令式面向对象编程或过程式编程的人。如果你的问题是 "里面有值吗?(真值或假值)", 你可以使用 .some
方法来验证里面的值。
[].some(el => el || !el);
function isEmpty(arr) { ... }
。[].length
得到0
时,这仍然比"它的长度是零吗?"听起来更好,而在某些情况下,0
是危险的。[].length > 0
说"它的长度是否大于零?"高级示例:
[ ].some(el => el || !el); // false
[null].some(el => el || !el); // true
[1, 3].some(el => el || !el); // true
如果数组[index]为空,请尝试这个
if (array[index] != null)
if(_.has(req,'documents')){
if (req.documents.length)
_.forEach(req.documents, function(document){
records.push(document);
});
} else {
}
if(_.has(req,'documents'))
是为了检查我们的请求对象是否有一个名为 documents
的属性,如果有该属性,则下一个 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) ) });
检查所有数组值是否为 null 或未定义的值:
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) ) });
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
在http://underscorejs.org/中查看更多示例
fn(){}
是语法错误,而且不清楚它如何帮助检查一个数组项是否存在于特定的索引位置。 - Oriol