如何检查JavaScript是否在某个数组索引处存在值?

JavaScript

小胖Jim

2020-03-12

这将用于测试位置“索引”处的值是否存在或是否有更好的方法:

if(arrayName[index]==""){
     // do stuff
}

第1154篇《如何检查JavaScript是否在某个数组索引处存在值?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

8个回答
前端飞云 2020.03.12

To check if it has never been defined or if it was deleted:

if(typeof arrayName[index]==="undefined"){
     //the index is not in the array
}

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):

if(typeof arrayName[index]==="undefined"||arrayName[index]){
     //the index is not defined or the value an empty value
}
神乐Harry 2020.03.12

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.

神奇飞云 2020.03.12

try this if array[index] is null

if (array[index] != null) 
MandyJinJin路易 2020.03.12

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
}
凯老丝 2020.03.12
if(arrayName.length > index && arrayName[index] !== null) {
    //arrayName[index] has a value
}
米亚GO 2020.03.12
if(!arrayName[index]){
     // do stuff
}
路易GO 2020.03.12

仅使用.length不安全,并且会在某些浏览器中导致错误。这是一个更好的解决方案:

if(array && array.length){   
   // not empty 
} else {
   // empty
}

或者,我们可以使用:

Object.keys(__array__).length
小哥GOItachi 2020.03.12

我们不能只是这样做:

if(arrayName.length > 0){   
    //or **if(arrayName.length)**
    //this array is not empty 
}else{
   //this array is empty
}

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android