简体   繁体   中英

Why this happen, javascript sparse array uninitiated

在此处输入图片说明

It seems the value is OK, but I don't know if this kind of programming is OK in javascript.

I try to avoid this kind of things. In my opinion it's better to use push to create array which you can go through with for loops.

Problem with this is that if you create things like this and then wanna do something with data you would end up with because you have to skip undefines.

for (var i = 0; i < arr.length; i++) {
   if (arr[i] != undefined) {
     // do something here
   }
}

When you get other developers on the code, it generates considerable number of WTF moments. I had to work with code which was using this kind of assignment of values in arrays so that index always corresponds with ID and it is nightmare to maintain and figure out what is going on.

Also the length of the arr will be reported 'incorrectly' because you only had one value inside, but length is 33.

If you need ID's or something, you can use

var arr = [];
arr.push({"id":32, "value": "this is element with id attribute 32"});

Edit:

If you need to retrieve something which has ID 32 in this case, you would do

for (var i = 0; i < arr.length; i++) {
   if (arr[i].id === 32) {
     // do something here
   }
}

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