簡體   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