【问题标题】:How to loop/iterate over a 2D array using every()?如何使用every()循环/迭代二维数组?
【发布时间】:2021-07-18 15:31:42
【问题描述】:

我找不到使用方法every() 的解决方案。我想看看每个坐标(x 和 y)是否

这是我的代码:

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

谢谢。

【问题讨论】:

    标签: javascript loops methods


    【解决方案1】:
    const shipLocation = [ [ 2, 3 ], [ 3, 3 ], [ 4, 3 ], [ 5, 3 ], [ 6, 3 ] ]
    const outOfBounds = shipLocation.every(cords=> (cords[0]<=10) && (cords[1]<=10))
    
    

    【讨论】:

    • 为什么返回false?它应该返回 true!
    • 你是对的,现在它正确地获取了坐标
    【解决方案2】:
    1. 您需要从您的函数中返回一个值(布尔值:true 或 false)。

    2. 您有嵌套数组,因此您需要在每个数组上使用 every并且再次使用 every 检查这些数组中的值是否小于或等于 10,确保您也从该回调返回 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));

    【讨论】:

    • 这算是嵌套循环吗?
    • 我猜是这样,但我更倾向于将嵌套循环与for in or for of 循环联系起来,而不是更多功能性的迭代代码。
    • 知道大 O 会是什么吗?
    • 你的数据集有多大?
    • 最大的是 2D 数组 5 个元素,每个是 2 个元素。
    【解决方案3】:
    • 您可以使用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);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-27
      • 2019-04-23
      • 2019-06-02
      • 1970-01-01
      • 2014-03-26
      • 1970-01-01
      • 2018-12-29
      • 1970-01-01
      相关资源
      最近更新 更多