本文翻译自:How do I check in JavaScript if a value exists at a certain array index?
Will this work for testing whether a value at position "index" exists or not, or is there a better way: 这是否可用于测试位置“索引”的值是否存在,或者是否有更好的方法:
if(arrayName[index]==""){
// do stuff
}
#1楼
参考:https://stackoom.com/question/BDCu/如果某个数组索引中存在某个值-如何检入JavaScript
#2楼
Can't we just do this: 我们不能这样做:
if(arrayName.length > 0){
//or **if(arrayName.length)**
//this array is not empty
}else{
//this array is empty
}
#3楼
if(arrayName.length > index && arrayName[index] !== null) {
//arrayName[index] has a value
}
#4楼
if(!arrayName[index]){
// do stuff
}
#5楼
All arrays in JavaScript contain array.length
elements, starting with array[0]
up until array[array.length - 1]
. JavaScript中的所有数组都包含array.length
元素,从array[0]
开始直到array[array.length - 1]
。 By definition, an array element with index i
is said to be part of the array if i
is between 0
and array.length - 1
inclusive. 根据定义,如果i
介于0
和array.length - 1
之间,则具有索引i
的数组元素被称为数组的一部分。
That is, JavaScript arrays are linear, starting with zero and going to a maximum, and arrays don't have a mechanism for excluding certain values or ranges from the array. 也就是说,JavaScript数组是线性的,从零开始并达到最大值,并且数组没有从数组中排除某些值或范围的机制。 To find out if a value exists at a given position index (where index is 0 or a positive integer), you literally just use 要确定给定位置索引(索引是0还是正整数)中是否存在值,您只需使用
if (index < array.length) {
// do stuff
}
However, it is possible for some array values to be null, undefined
, NaN
, Infinity
, 0, or a whole host of different values. 然而,可能的是一些数组值为空, undefined
, NaN
, Infinity
,0,或不同的值的整个主机。 For example, if you add array values by increasing the array.length
property, any new values will be undefined
. 例如,如果通过增加array.length
属性来添加数组值,则任何新值都将是undefined
。
To determine if a given value is something meaningful, or has been defined. 确定给定值是有意义的还是已定义的。 That is, not undefined
, or null
: 也就是说, 没有 undefined
,或null
:
if (typeof array[index] !== 'undefined') {
or 要么
if (typeof array[index] !== 'undefined' && array[index] !== null) {
Interestingly, because of JavaScript's comparison rules, my last example can be optimised down to this: 有趣的是,由于JavaScript的比较规则,我的最后一个例子可以优化到这个:
if (array[index] != null) {
// The == and != operators consider null equal to only null or undefined
}
#6楼
if(typeof arr ==='object' && arr instanceof Array ){
if(!arr.length){
println 'empty'
}else{
printn 'not Empty'
}
}else{
println 'Null'
}
If you mean by 'Null' -> Its elements are null or equals to '' , in this case : Check if the array is empty after filtering all 'null' elements 如果你的意思是'Null' - >它的元素是null或等于'',在这种情况下:在过滤所有'null'元素后检查数组是否为空
if(!arr.clean().length){return 'is null'}
Of course ,Add Clean method before : 当然,之前添加Clean方法:
Array.prototype.clean=function(){return this.filter(function(e){return (typeof e !=='undefined')&&(e!= null)&&(e!='')})}