0

this is weird, anybody can explain me this strange result. Am building a editor with a sprite register.

So example

var LIST = []; // array list
LIST[4] = {}; // register data to id 4, OK
LIST[3] = {}; // register data to id 3, OK

// now check
LIST[2] === void 0; // return true , OK
LIST.length; // return 5 OK

LIST.indexOf(void 0); // return -1 WAIT WHAT ??? WHY?

LIST[2] = void 0;
LIST.indexOf(void 0); // return 2 OK
jon
  • 1,494
  • 3
  • 16
  • 29
  • 1
    Same reason why [`forEach` doesn't work on sparse arrays](https://stackoverflow.com/questions/23460301/foreach-on-array-of-undefined-created-by-array-constructor), for example. Consider `list = []`, then `list[2] === undefined` but `list.includes(undefined) == false`. `list[2]` doesn't actually exist as a property, so it's not considered on the question whether the array contains an `undefined` value. – Bergi Jan 26 '19 at 17:55
  • `arr.findIndex((i)=>i)` seem work but need pass callBack and this is bad for performance, but i don't have choice. – jon Feb 12 '19 at 09:23
  • It's unclear what you are trying to do. `indexOf` should work just fine, just make sure you are not creating sparse arrays (which are bad for performance). Assign `LIST[0] = LIST[1] = LIST[2] = undefined;` and it will be found. And no, callbacks are not bad for performance, in the native array iteration methods everything gets inlined and is as fast as a loop. – Bergi Feb 12 '19 at 12:06

0 Answers0