这将用于测试位置“索引”处的值是否存在或是否有更好的方法:
if(arrayName[index]==""){
// do stuff
}
这将用于测试位置“索引”处的值是否存在或是否有更好的方法:
if(arrayName[index]==""){
// do stuff
}
I ran into this issue using laravel datatables. I was storing a JSON value called properties
in an activity log and wanted to show a button based on this value being empty or not.
Well, datatables was interpreting this as an array if it was empty, and an object if it was not, therefore, the following solution worked for me:
render: function (data, type, full) {
if (full.properties.length !== 0) {
// do stuff
}
}
An object does not have a length property.
try this if array[index] is null
if (array[index] != null)
I would like to point out something a few seem to have missed: namely it is possible to have an "empty" array position in the middle of your array. Consider the following:
let arr = [0, 1, 2, 3, 4, 5]
delete arr[3]
console.log(arr) // [0, 1, 2, empty, 4, 5]
console.log(arr[3]) // undefined
The natural way to check would then be to see whether the array member is undefined, I am unsure if other ways exists
if (arr[index] === undefined) {
// member does not exist
}
if(arrayName.length > index && arrayName[index] !== null) {
//arrayName[index] has a value
}
if(!arrayName[index]){
// do stuff
}
仅使用.length
不安全,并且会在某些浏览器中导致错误。这是一个更好的解决方案:
if(array && array.length){
// not empty
} else {
// empty
}
或者,我们可以使用:
Object.keys(__array__).length
我们不能只是这样做:
if(arrayName.length > 0){
//or **if(arrayName.length)**
//this array is not empty
}else{
//this array is empty
}
To check if it has never been defined or if it was deleted:
also works with associative arrays and arrays where you deleted some index
To check if it was never been defined, was deleted OR is a null or logical empty value (NaN, empty string, false):