【问题标题】:assign values to numeric indexed multidimensional array jquery为数字索引多维数组jquery赋值
【发布时间】:2014-04-26 16:46:35
【问题描述】:

我想使用 .each() 循环一个 jquery 选择器并将值分配给一个多维数组 $record。 这是我尝试过的,但它不起作用

查询:

var $record = new Array(),
    i=0,
    x,y;
$("td").each(function(){       
    x = Math.floor((i+1)/4),
    y = i%4;
    $record[x][y] = true;    
    i++;
});

CHROME CONSOLE ERROR: Uncaught TypeError: Cannot set property '0' of undefined

【问题讨论】:

  • 这是一个看起来很奇怪的数组,无法想象你会如何访问它并找出密钥?

标签: javascript jquery multidimensional-array


【解决方案1】:

该错误正在引发,因为您没有定义内部数组。

试试,

$("td").each(function(){       
    x = Math.floor((i+1)/4),
    y = i%4;
    if(!$.isArray($record[x])) { $record[x] = []; }
    $record[x][y] = true;    
    i++;
});

【讨论】:

    【解决方案2】:

    考虑一下

    var record = [],
        i = 0,
        x = Math.floor((i+1)/4),
        y = Math.floor((i+1)/4)
    
    console.log(record); // 0
    console.log(record[0]); // undefined
    console.log(record[x][y]); // Uncaught TypeError: 
                               // Cannot read property '0' of undefined 
    

    第一次迭代,i0。您正在尝试访问一个不存在的元素。或者更具体地说,数组上的属性0,如果索引0 上有一个元素,则该属性将存在。

    换句话说,如果你向数组中添加一些东西,它会得到它的属性:

    record[0] = 'something';
    console.log(record['0'], record.hasOwnProperty('0')); // 'something', true
    

    【讨论】:

      猜你喜欢
      • 2014-11-15
      • 1970-01-01
      • 2015-06-16
      • 1970-01-01
      • 1970-01-01
      • 2021-10-08
      • 2016-05-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多