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); } }
Advertisement
Answer
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); } }