2016-07-22 58 views
0

如何返回一個最大值設置的數組,在這種情況下,它們大於5?用最大值限制迭代數組並返回

arr.forEach(function(index, theArray) { 
    if (theArray[index] > 5) theArray[index] = 5 
}) 
console.log(arr) // [5.5, 0.1 8.4, 4.3, etc] 

[5, 0.1, 5, 4.3, etc]

回答

3

可以使用mapMath.min

arr = arr.map(n => Math.min(n, 5)); 
+0

對於大的輸入,並'map'最終創建的元素相對於在適當位置變形例的第二映射副本。還是編譯器足夠聰明,看到你立即覆蓋'arr'? – arcyqwerty

+0

@arcyqwerty不確定實現什麼,但是,它可能會浪費內存以用於巨大的數組。但在這種情況下,我會使用typedarrays而不是普通的數組。 – Oriol

1

您需要添加一個參數吃從forEach功能的當前元素。

輸入

var arr = [5.5, 0.1, 8.4, 4.3]; 

代碼

arr.forEach(function(_, index, theArray) { 
    if (theArray[index] > 5) theArray[index] = 5; 
}) 
console.log(arr) 

輸出

[5,0.1%,5,4.3]

參考文檔:

語法

arr.forEach(callback[, thisArg]) 

參數

  • 回調

    功能以執行用於每個元素,以三個參數:

    • CurrentValue的

      陣列中正在處理的當前元素。

    • 索引

      當前元素的索引陣列中的正在處理中。

    • 陣列

      的陣列的forEach()被施加到。

  • thisArg

    可選。在執行回調時使用此值。

返回值

undefined 

您的代碼還可以縮短一點,採取這種其他未使用的變量的優勢。

arr.forEach(function(element, index, theArray) { 
    if (element > 5) theArray[index] = 5; 
} 

請注意,如果你想做到這一點沒有突變的原始數組,你也有地圖的選項。

arr.map(function(e) { return Math.max(e, 5); }