簡體   English   中英

map function 返回 1 boolean 值,而不是 Z84E2C64F38F78BA3EA5C905DA27A 值的數組

[英]map function to return 1 boolean value, instead of an array of boolean values

假設你有一個這樣的數組:

arrayExample = [1, 2, 3, 4, 5, 6, 7]

我想使用 map function 遍歷 arrayExample 並在所有數字都小於 8 時返回true ,否則返回false 但是,當我這樣做時,我會得到一組真值(例如:[true, true, true... etc])

我可以只返回 1 個值嗎?

到目前為止,這是我的代碼:

 var testBoolean = true; var array = [1,2,3,4,5,6,7]; testBoolean = array.map(m => { //if a number in the array is >=8, changes the testBoolean to false and return false only if(m >= 8) { return false; } //VS code said I had to have a return here, I believe its because I need to have in case m < 8 (edited after reading a comment) return true; }) //prints an array [true,true,true,true,true,true,true] document.write(testBoolean);

我對“map”有點陌生,但我相信它會這樣做,因為它為每個元素返回一個值,只是對如何制作它感到困惑,所以它返回 1 truefalse

對於這樣的事情.map()不是正確的工具。 .map()用於將數組中的所有元素轉換為新元素(即:將每個元素映射到新的轉換值)。 因此, .map()將始終返回一個數組(除非有意修改此行為)。 相反,您可以為此使用.every() ,它將檢查數組中的所有元素是否符合您的條件(即:如果您的 function 為每個元素返回 true,那么您的結果將是 true,否則您將得到錯誤)。 如果.every()方法找到一個您的回調 function 為其返回 false 的元素,它將提前終止,這有助於提高效率:

 const array = [1, 2, 3, 4, 5, 6, 7]; const testBoolean = array.every(m => { if (m >= 8) { return false; } return true; }); console.log(testBoolean);

這可以寫得更簡潔,只返回m < 8的結果(這將評估為truefalse

 const array = [1,2,3,4,5,6,7]; const testBoolean = array.every(m => m < 8); console.log(testBoolean);

最簡單的解決方案是使用.some()

我們不需要檢查每個值。 我們需要找到不小於 8 的第一個值。

 const array = [1, 2, 3, 4, 5, 6, 7] const testBoolean =.array.some(m => m >= 8) console.log(testBoolean)

從更一般的角度來看,如果您想從 Array 返回單個值, .reduce()是您的朋友。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

特別是在你的情況下,你可以做

array.reduce(function(accumulator, currentVal, i, arr) {
  return accumulator && currentVal < 8;
}, true));

因此.reduce()使用初始值true遍歷您的數組並返回“先前”值(累加器)以及當前值是否小於 8。

你可以把它想象成

(true && (a[0] < 8 && (a[1] < 8... )))

每次迭代的返回值成為下一次的accumulator 這樣,您不僅可以進行數學運算,還可以將某個形狀的數組(例如{w:0, h:0}對象的數組)更改為另一個的 output(例如,單個數字是所有從每個wh計算的斜邊)。

const fn = (z)=>{
  if(z>=8){
    return true;
  }else{
    return false;
   }
}

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const mappedArray = array.map(fn);
 
//for value

const filterdArray = array.filter(fn)

console.log(mappedArray)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM