在多维数组中查找相邻差异

时间:2017-12-29 09:52:31

标签: javascript arrays multidimensional-array

我有一个带有以下元素的js数组

var xy = [
  [11,21],
  [20,10],
  [36,70],
  [42,70],
]

我想找到每个相邻元素之间的差异并存储在另一个数组中

xdiff = [9,16,6]
ydiff = [11,60,0]

我试过

for(i=0; i<xy.length; i++)
{
  xdiff.push(Math.abs(xy[i][0]-xy[i+1][0]))
  ydiff.push(Math.abs(xy[i][1]-xy[i+1][1]))
}

但它输出错误。

1 个答案:

答案 0 :(得分:1)

当到达最后xy坐标时,尝试会遇到错误。它会尝试使用xy[i + 1]向前看,但会返回undefined

因此错误:Cannot read property '0' of undefined

要解决此问题,请在最后一个元素之前循环到元素:

var xy = [
  [11, 21],
  [20, 10],
  [36, 70],
  [42, 70],
],
  xdiff = [],
  ydiff = [];
    
for (i = 0; i < xy.length - 1; i++) {
  //                     ^^^^ stop before the last element

  xdiff.push(Math.abs(xy[i][0] - xy[i + 1][0]))
  ydiff.push(Math.abs(xy[i][1] - xy[i + 1][1]))
}

console.log(xdiff, ydiff);