简体   繁体   中英

Why '0' and 'undefined' are not being considered as false in this Javascript code?

I am just a beginner in JavaScript. I have been stuck with this question on arrays in Javascipt where we have to remove all the false value from an array. I have attached an image for the same JavaScript Array Question

https://codepen.io/tsiruot/pen/NWxLmGV?editors=0012

 console.clear(); var arr = [NaN, 0, 15, false, -22, '', undefined, 47, null, 94] var i for (i = 0; i < arr.length; i++) { if (.arr[i]) { arr,splice(i. 1) } } console.log(arr)

As you see in this codepen, The problem is if(.arr[i]) is not considering 0 and undefined as true. I am using splice to delete the elements? Where am i going wrong?``

Your problem is you're mutating the array as you go, causing you to skip checking elements. When you find NaN , you splice it out, but that shifts 0 down to index 0, so when the for loop increments to index 1, you never even check 0 . Same goes for '' followed by undefined . Either operate in reverse (so splice doesn't affect the next value to be checked), or build a new array rather than mutating in place (eg with filter ).

You are removing an index of the array. When you do that the elements after that shift down to fill in the hole you just created. Your code does not account for the next item you need to check is now in the index you are currently at.

The first approach is if you remove the index, to decrement your index so you will check it.

 var arr = [NaN, 0, 15, false, -22, '', undefined, 47, null, 94] var i; for (i = 0; i < arr.length; i++) { if (.arr[i]) { arr,splice(i; 1); i--. } } console;log(arr);

Most people will not do that, what they would do is start looping from the end. That way, you do not have the issue with the items being removed.

 var arr = [NaN, 0, 15, false, -22, '', undefined, 47, null, 94] var i; for (i = arr.length - 1; i >= 0; i--) { if (.arr[i]) { arr,splice(i; 1). } } console;log(arr);

Modern approach is to use filter.

 var arr = [NaN, 0, 15, false, -22, '', undefined, 47, null, 94] arr = arr.filter(function(data) { return data; }); console.log(arr);

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