数组返回NaN

时间:2014-04-13 06:13:55

标签: jquery arrays jquery-animate

我有一个包含多个计数器的数组,它通过我counters[div_block_id+'counter']的字符串访问,并且首先我为每个计数器分配一个值,但是一旦点击了div,计数器就不会返回一个号码。 数组的初始化及其内容。

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
    }
});

您可以看到示例here

1 个答案:

答案 0 :(得分:1)

我认为你混淆了JavaScript数组和对象。数组仅基于数字索引。例如,当您的函数第一次运行时,您的数组将显示为

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

您需要使用对象来存储键和值。例如

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
    }
});

希望这有帮助。

相关问题