0

The code is the following:

$('input').click(function(){
    window.array[$(this).attr('id')]=true;
    console.log('Input id: '+$(this).attr('id')+' - Num:'+window.array.length+
        ' - Array value:'+window.array[$(this).attr('id')]);
    alert(window.array.join('\n'));
});

The behavior is very strange: when the event is fired, in the console I can read Input id: example_id - Num:0 - Array value:true, then in the alert I get undefined (empty array? but the console told me the correct value!).

When I click on another input, exactly the same thing happens, such as the previous event hasn't been fired. It seems that the callback function creates an array every time it's called, but I'm using window object, and I was told that attaching arrays to window object is the same of global vars!

Can you explain me this strange behavior?

1
  • If your array index ($(this).attr('id')) is not an number (not a string of a number, a actual number), you have created an object, not an array. Arrays can only have numeric indexes. Commented Dec 7, 2012 at 21:41

2 Answers 2

1

The length property of an array is its largest numeric property plus one (or zero if it has no numeric properties). So setting non-numeric properties on an array does not change its length.

join only effects numeric properties as well. Still, the result should be an empty string, not undefined. Are you sure you are using a normal array?

Sign up to request clarification or add additional context in comments.

Comments

0

Your situation demands that you use an object since you need to use a string as your "id".

if you have defined:

window.array = [ ]

and write:

window.array["id1"] = true; // WRONG!

The above simply means that you'll get:

window.array["id1"] //true but window.array is still [ ]

which is because window.array, though an array is still an object in JavaScript and you can add properties to it but the usage is wrong. To add to an array, you need integers(or integers in the form of string) as indexes.

window.array[1] = true; // OR window.array["1"] = true (!! even this works)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.