Reputation: 601
Similar to something I posted recently but not the same :-)
I'm trying to test in GAS if an array contains any empty values. includes()
doesn't seem to be supported so I've been trying to use index but failing miserably. My test code is below with the empty element before 7
var e = [1,2,3,4,2,4,,7];
var x = 0;
if (e.indexOf() ==-1){
var x = 'No blanks';
}
But no matter what I try it always passes. I've already tried indexOf("")
, indexOf('')
& indexOf()
.
I've run out of things to try so any help would be greatly received!
Upvotes: 1
Views: 1821
Reputation: 5250
To find the keys of all empty elements if there any:
var e = [1,,3,4,2,,7];
var o = Object.keys(e);
m = [];
o.forEach(function(e,i){
if(i>0 && e-o[i-1]>1){
m.push(e-1)
}
})
console.log(m);
console.log(m.length);
Upvotes: 0
Reputation: 370679
What you have there is a spare array. The missing element there isn't the empty string, it's just not there at all. Because the missing element there isn't enumerable either, it won't show up when you use array methods like indexOf
. You might check to see whether the number of keys is equal to the length
of the array:
var e = [1,2,3,4,2,4,,7];
var x = Object.keys(e).length === e.length
? 'OK!'
: 'Blank element detected';
console.log(x);
// constrast with a normal array:
e = [1,2,3,4,2,4,7];
x = Object.keys(e).length === e.length
? 'OK!'
: 'Blank element detected';
console.log(x);
Upvotes: 2