Created
November 9, 2010 22:12
-
-
Save furf/669927 to your computer and use it in GitHub Desktop.
while looking for a way to conditionally push something into an array, i discovered the following javascript black hole
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var arr = []; | |
| arr.push(1); | |
| arr.push(arr); | |
| arr.push(3); | |
| arr.forEach(function (item, i) { | |
| console.log(i, item); | |
| }); | |
| // 0 1 | |
| // 2 3 | |
| // will not iterate the self-referential member -- like it's not even there! | |
| console.log(arr.join(';')); | |
| // "1;;3" | |
| console.log(arr.toString()); | |
| // "1,,3" | |
| // but will return an empty string when joined or toString'd |
It's OK with JS (by the spec and in SM implementation) -- all elements are visited correctly; only non-existing elements shouldn't be visited. It's a bug of the console object. Replace console.log with alert for check.
Dmitry.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Saw the same results except for the arr.forEach statement, which for me (in Chrome 7 on Mac) returned:
0 1
1 [1, >Array[3], 3]
2 3
and then I tried arr.forEach(function(item, i) { console.log(i,item.toString());}), which yielded:
0 "1"
1 "1,,3"
2 "3"