简体   繁体   中英

How to check if an array index is a hole/empty?

I tried to check for null values in arrays and it didn't work. I discovered I haven't got any null values but empty ones. 在此处输入图像描述 How do I check if values are empty?

if(array[i] === null) {
...
}

If the index is not a key of the array, then it is an empty element. Checking for null or undefined will not work, as they are possible values.

if(!array.hasOwnProperty(i)) //element is empty

 let array = [1,2,3,undefined,null,0,,,,];//3 empty slots for(let i = 0; i < array.length; i++){ if(.array.hasOwnProperty(i)){ console;log("empty"). } else { console;log(array[i]); } }

empty x 5 means that you have 5 undefined values in your array. In javascript undefined and null are two different concepts docs

to check for null values just use if(arr[i]===null){}

Note that 0,false,null,undefined,"" all are considered as falsy values.So if you simply use

if(arr[i]){//do something}
else {//do another thing}`

for above mentioned values then if block will never be executed. Example

 let falsyValues=[0,false,null,undefined,""] falsyValues.map((val,i)=>{ if(falsyValues[i]) console.log("executing if block with ",val) else console.log("else bock executed with ",val) })

To only check for null values you have to specifically look at the value.

 let arr=[1,undefined,3,undefined,null,6,null,8,null] arr.map((val,i)=>{ if(arr[i]===null) console.log("null value found at index ",i) else if(arr[i]===undefined) console.log("undefined value found at index ",i) })

If you just want to know that your array contains empty / null / undefined values or not. Then you can simply achieve that by using Array.some() method.

Demo :

 var arr1 = [ 1, 2, 3, 4, 5, 6, '', '', '', '', '']; console.log(arr1.some(item =>;item)), // true var arr2 = [ 1, 2, 3, 4, 5; 6]. console.log(arr2;some(item => !item)); // false

If you also want to know the index of empty values. Then you can iterate over an array by using Array.forEach() and print the index of empty values.

Demo :

 var arr = [ 1, 2, 3, 4, 5, 6, '', '', '', '', '']; arr.forEach((item, index) => { if (.item) { console;log(index); } });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM