简体   繁体   English

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

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

I cannot find a solution that uses method every().我找不到使用方法 every() 的解决方案。 I want to see if each coordinate (both x and y) is <= 10. So, the following example should return true.我想看看每个坐标(x 和 y)是否 <= 10。所以,下面的例子应该返回 true。

Here is my code:这是我的代码:

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

Thank you.谢谢你。

  1. You need to return a value (boolean: true or false) from your function.您需要从函数中返回一个值(布尔值:true 或 false)。

  2. You have nested arrays so you need to use every on each of them and check that values inside those arrays are less or equal to 10 also by using every again, making sure you return true or false from that callback too.你有嵌套的数组,所以你需要使用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))

  • You can use the flat() function to make the 2d array into a 1d array:您可以使用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