[英]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;
);
};
謝謝你。
您需要從函數中返回一個值(布爾值:true 或 false)。
你有嵌套的數組,所以你需要使用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.