Ch32k0
Ch32k0

Reputation: 244

Array returns NaN

I have a array that contains multiple counters and it's accessed via a string that i counters[div_block_id+'counter'] and at first I assign a value of zero to each counter but once the div is clicked the counter returns not a number. Initialization of array and its content.

var counters = new Array();
// Searches for every div that have an id attribute
$('div').each(function () {
    if (!this.id) {} else {
        var id = this.id + '_counter';
        counters.push(id); //add id to counters array 
        counters[id] = 0; //initialize as 0 the counter of corresponding id 
        console.log(counters); //Logs the array
    }
});

You can see a sample here

Upvotes: 0

Views: 1127

Answers (1)

NoGray
NoGray

Reputation: 1149

I think you are confusing JavaScript arrays and objects. Arrays are based on numerical indices only. For example, when the first time your function runs, you'll array will look as

counters.push(id); // your array will be counters[0] = id;
counters[id] = 0; // nothing will happen because it's an invalid index

You need to use an object to store keys and values. For example

var counters = {}; // short code for object
// Searches for every div that have an id attribute
$('div').each(function () {
    if (!this.id) {} else {
        var id = this.id + '_counter';
        counters[id] = 0; //initialize as 0 the counter of corresponding id 
        console.log(counters[id]); //Logs the array
    }
});

Hope this helps.

Upvotes: 1

Related Questions