Jump to content
Larry Ullman's Book Forums

Chapter 6: Explicitely Defining Sparsely Populated Arrays And Conditions


 Share

Recommended Posts

In chapter 6, on page 230, it is said that when you, intentionally, want to create a sparsely populated arrays it is best to be explicit about it in the following way:

 

var myList = [1, undefined, 3, undefined, 5];

 

However, this leads to a problem when using an if in condition in a for loop, like so:

 

for (var i = 0, count = myList.length; i < count; i++) {
if (i in myList) {
console.log(myList[i]);
}
}

 

Under normal circumstances, in a sparsely populated array, this would lead to only the defined elements (1, 3 and 5) outputting to the console. But when explicitely using undefined to create these "holes", it leads to the entire list, including undefined elements being outputted.

 

Full example:

 

var myList = [1, undefined, 3, undefined, 5];
for (var i = 0, count = myList.length; i < count; i++) {
if (i in myList) {
console.log(myList[i]);
}
}
1
undefined
3
undefined
5

 

This, however, does work:

 

var myList = [1, , 3, , 5];
for (var i = 0, count = myList.length; i < count; i++) {
if (i in myList) {
console.log(myList[i]);
}
}
1
3
5

Link to comment
Share on other sites

Actually, your code is working the way it's supposed to, but most likely not the way you're expecting it to.

The in keyword is use to check for the existence of property names, not values. Please see the following for details:

http://www.aptana.co...n operator.html

 

In your array myList, the property names 1, 2, 3, 4 and 5 all exist, even though the value undefined is set for two of them. As such, all values are reported to the console when you use the expression if (i in myList).

 

By slightly amending your if statement though, you can easily get what you want.

The following will work fine.

 

for (var i = 0, count = myList.length; i < count; i++) {
if (myList[i]) {
console.log(myList[i]);
}
}

 

That answer your question?

  • Upvote 1
Link to comment
Share on other sites

 Share

×
×
  • Create New...