Issue
I have a JavaScript array with some empty (maybe null or undefined) elements. I need to find those empty indexes (1 and 3).
['red',,'orange',,'blue','white','black']
But my solution is not working:
for (let i = 0; i < array.length; i++) {
if (array[i] === undefined) { // Same problem with null or ''
console.log('No color: ' + i);
}
}
Snippet:
const array = ['red', , 'orange', , 'blue', 'white', 'black'];
for (let i = 0; i < array.length; i++) {
if (array[i] === undefined) { // Same problem with null or ''
console.log('No color: ' + i);
}
}
Solution
Use a blank string to compare to get the answer you desire. If you also want to check for undefined you can use logical or to check both of them.
const array = ['red','', 'orange',, 'blue', 'white', 'black'];
for (let i = 0; i < array.length; i++) {
if (array[i] === '' || array[i] === undefined) {
console.log('No color: ' + i);
}
}
Answered By - varisha15 Answer Checked By - Willingham (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.