2017-02-27 62 views
-2

我有數組元素,我試圖乘以2只使用過濾器方法(不是地圖)。我期待的輸出結果如下所示[2,4,6,8 ,10]。這裏是我的代碼如何加倍數組元素的值

var array = [1,2,3,4,5]; 
    array.filter(val => val * 2); 
+0

是的,簡單的方法是使用地圖,但我有興趣嘗試使用過濾器。 –

+2

不可以。你不應該使用過濾器。這不是過濾器的工作原理。它只是用於過濾。 –

+1

我想你需要閱讀過濾方法的概念。 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter –

回答

4

filter,你應該在這種情況下使用map功能。

var array = [1,2,3,4,5]; 
array = array.map(function(val){return val*2;}); 
console.log(array); 

Demo

0

嘗試使用此

var new_array = array.map(function(e) { 
     e = e*2; 
     return e; 
    }); 
1

僅使用過濾器的方法...你可以嘗試使用這就像一個迭代器(注意,這是不過濾應該是怎樣使用):

var array = [1,2,3,4,5]; 
array.filter(function (val, i, array) { array[i] = val * 2; }); 
//array now has [2,4,6,8,10] 

這是醜陋的,但這是你會做什麼,如果你可以o只需使用filter

0

首先您需要了解map,filterreduce的功能。

根據您的要求,它應該是map的功能,但是您需要filter這並不明顯。

地圖:

When you call map on an array, it executes that callback on every 
element within it, returning a new array with all of the values 
that the callback returned. 

過濾

filter executes that callback on each element of the array, and spits 
out a new array containing only the elements for which the callback returned true. 

let items = ['1','2','3','4','5']; 
 

 
let numbers = items.map(item=>item*2); 
 

 
console.log(items); 
 
console.log(numbers);

0

如果你真的要使用過濾器(),你不需經過d到:

Array.prototype.filter = Array.prototype.map 
var array = [1,2,3,4,5]; 
array.filter(val => val * 2); 

但請不要。