这将用于测试一个值在位置索引是否存在,或者有更好的方法:
if(arrayName[index]==""){
// do stuff
}
这将用于测试一个值在位置索引是否存在,或者有更好的方法:
if(arrayName[index]==""){
// do stuff
}
当前回答
你可以使用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(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/
如果数组[index]为空,请尝试此操作
if (array[index] != null)
我建议创建一个这样的函数:
function isEmptyEl(array, i) {
return !(array[i]);
}
你可以这样称呼它:
if (isEmptyEl(arrayName, indexVal)) {
console.log('arrayName[' + indexVal + '] is empty');
}
强制开发人员使用isemptyl接口将捕获输入错误,例如未定义的arrayName或indexVal变量。
(在使用Javascript编程时,防御性编程通常是一个很好的实践。)
如果没有定义arrayName,就会抛出这样的错误:
Uncaught ReferenceError: arrayName is not defined
at <anonymous>:2:15
at Object.InjectedScript._evaluateOn (<anonymous>:895:140)
at Object.InjectedScript._evaluateAndWrap (<anonymous>:828:34)
at Object.InjectedScript.evaluate (<anonymous>:694:21)
未定义的indexVal也有类似的结果。
如果数组或索引值不存在,就会得到一个错误。
对于有效的输入,如果arrayName[indexVal]是以下任意一个,你只会得到一个true:
零 未定义的 南 空字符串 0 假
我们就不能这样做吗
if(arrayName.length > 0){
//or **if(arrayName.length)**
//this array is not empty
}else{
//this array is empty
}