本文翻譯自: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!='')})}