如何加倍数组元素的值
问题描述:
我有数组元素,我试图乘以2只使用过滤器方法(不是地图)。我期待的输出结果如下所示[2,4,6,8 ,10]。这里是我的代码如何加倍数组元素的值
var array = [1,2,3,4,5];
array.filter(val => val * 2);
答
尝试使用此
var new_array = array.map(function(e) {
e = e*2;
return e;
});
答
仅使用过滤器的方法...你可以尝试使用这就像一个迭代器(注意,这是不过滤应该是怎样使用):
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
答
首先您需要了解map
,filter
和reduce
的功能。
根据您的要求,它应该是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);
答
如果你真的要使用过滤器(),你不需经过d到:
Array.prototype.filter = Array.prototype.map
var array = [1,2,3,4,5];
array.filter(val => val * 2);
但请不要。
是的,简单的方法是使用地图,但我有兴趣尝试使用过滤器。 –
不可以。你不应该使用过滤器。这不是过滤器的工作原理。它只是用于过滤。 –
我想你需要阅读过滤方法的概念。 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter –