我不明白为什么下面的代码在console.log中给出了filter函数和return函数中不同的结果:
function expandedForm(num) {
let arr = num.toString().split('').reverse().filter(function(el, ind){
console.log("iter:"+ el * Math.pow(10,ind));
return (el*Math.pow(10,ind))
});
console.log(arr);
return arr;
}
expandedForm(402);
给出如下内容:
iter:2
iter:0
iter:400
[ '2', '4' ]
=> [ '2', '4' ]编辑:显然,我还不够清楚。直截了当地说,为什么我在console.log中得到400,在过滤器中得到4?因此,问题更多地涉及到表达式el * Math.pow(10,ind)的评估。
发布于 2018-03-30 19:07:49
因为数组上的筛选器不操作数组中的元素。
例如:
const arr = [1, 2, 3];
const newArr = arr.filter(e => {
const newElement = e * 100;
return newElement;
}在这里,我们期望newArray是100,200,300,但我们收到它1,2,3。
原因--从过滤器返回值只是出于真/假的考虑,它实际上并不返回值。这就是为什么您没有得到0的值的原因。
如果您想要输出2,0,400,可以尝试下面的代码
const arr = num.toString().split('').reverse().map((el, ind) => {
return (el * Math.pow(10,ind));
});如果你想要一个2400的输出,
const arr = num.toString().split('').reverse().map((el, ind) => {
return (el * Math.pow(10,ind));
}).filter(e => e);发布于 2018-03-28 17:22:20
num.split('')返回一个数组['2', '0', '4'],
num.split('').filter(function(){ return handler()})在hander() is true时返回元素,然后第二个自定义为'0',其最终结果为0,因此它将不保留该元素。
最后,再使用程序是['2', '4']
parameter=callback).:(查看定义了Array.prototype.filter()上的描述
语法
var newArray = arr.filter(callback[, thisArg])参数
callback
Function is a predicate, to test each element of the array. Return true to keep the element, false otherwise, taking three arguments:
element
The current element being processed in the array.
indexOptional
The index of the current element being processed in the array.
arrayOptional
The array filter was called upon.
thisArg Optional
Optional. Value to use as this when executing callback. 发布于 2018-03-28 17:22:08
您需要阅读.filter function 对象/数组/筛选器的文档。
一个具有通过测试的元素的新数组。如果没有任何元素通过测试,则将返回一个空数组。
从过滤器函数返回什么并不重要,它只关心每个索引是否为false。因为402中有0,所以它跳过中间元素,只返回>0的元素。
https://stackoverflow.com/questions/49540544
复制相似问题