[英]How do I create a sparse array in javascript through iteration?
I wrote this code to scrape a sparse array from a series of dom elements. 我编写此代码是从一系列dom元素中刮取一个稀疏数组。 when done in one dimension the code works but in 2 dimensions it fails. 一维完成时,代码有效,但二维中失败。 Is there something i'm missing? 有什么我想念的吗?
23 function initCellHover(){
24 $cells.each(function(){
25 var arrayX = $(this).position().left/cellWidth;
26 var arrayY = $(this).position().top/cellHeight;
27 var arrayValue = $(this);
28 cellLookup[arrayX][arrayY] = arrayValue;
29 });
30 }
In line 28 you may be referring to a property of undefined. 在第28行中,您可能引用的是undefined属性。 It makes sense to check, if there already is a property in the array and add it, if needed: 检查数组中是否已存在属性,并在需要时添加它是有意义的:
cellLookup[arrayX] = cellLookup[arrayX] || [];
cellLookup[arrayX][arrayY] = arrayValue;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.