Skip to content

Instantly share code, notes, and snippets.

@furf
Created November 9, 2010 22:12
Show Gist options
  • Select an option

  • Save furf/669927 to your computer and use it in GitHub Desktop.

Select an option

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
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
@wlmeurer

wlmeurer commented Nov 9, 2010

Copy link
Copy Markdown

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"

@DmitrySoshnikov

Copy link
Copy Markdown

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