繁体   English   中英

如何使用every()循环/迭代二维数组?

[英]How to loop/iterate over a 2D array using every()?

我找不到使用方法 every() 的解决方案。 我想看看每个坐标(x 和 y)是否 <= 10。所以,下面的例子应该返回 true。

这是我的代码:

const shipLocation = [ [ 2, 3 ], [ 3, 3 ], [ 4, 3 ], [ 5, 3 ], [ 6, 3 ] ]
const outOfBounds = function (shipLocation) {
    Array.every(locationPoint => 
      // code here!
      locationPoint <= 10;
    );
  };

谢谢你。

  1. 您需要从函数中返回一个值(布尔值:true 或 false)。

  2. 你有嵌套的数组,所以你需要使用every他们每个人,并检查这些阵列内部的值是小于或等于10也通过every一次,确保你返回true或false从该回调了。

 const shipLocation=[[2,1],[3,3],[4,3],[5,3],[6,3]] const shipLocation2=[[2,41],[3,3],[4,3],[5,3],[6,3]]; function outOfBounds(shipLocation) { // For every ship location array return shipLocation.every(arr => { // Return whether every value is <= 10 return arr.every(el => el <= 10); }); }; console.log(outOfBounds(shipLocation)); console.log(outOfBounds(shipLocation2));

const shipLocation = [ [ 2, 3 ], [ 3, 3 ], [ 4, 3 ], [ 5, 3 ], [ 6, 3 ] ]
const outOfBounds = shipLocation.every(cords=> (cords[0]<=10) && (cords[1]<=10))

  • 您可以使用flat()函数将二维数组变成一维数组:

 const shipLocation = [ [ 2, 3 ], [ 3, 3 ], [ 4, 3 ], [ 5, 3 ], [ 6, 3 ] ]; const outOfBounds = shipLocation.flat().every(locationPoint => locationPoint <= 10 // do not put ";" ); console.log(outOfBounds);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM