我不明白为什么下面的代码在 filter
函数内的 console.log
和 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)
最佳答案
因为数组上的过滤器不会操作数组中的元素
例如:
const arr = [1, 2, 3];
const newArr = arr.filter(e => {
const newElement = e * 100;
return newElement;
}
这里我们期望 newArray 为 [100, 200, 300],但我们收到的是 [1, 2, 3]。
原因 - 从过滤器返回的值只是为了考虑真/假,它实际上并不返回该值。这就是为什么您没有获得 0 值(value)的原因。
如果你想要输出 [2, 0, 400],可以尝试下面的代码
const arr = num.toString().split('').reverse().map((el, ind) => {
return (el * Math.pow(10,ind));
});
如果您想要输出为 [2, 400],
const arr = num.toString().split('').reverse().map((el, ind) => {
return (el * Math.pow(10,ind));
}).filter(e => e);
关于javascript - console.log 与返回 : different results (JS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49540544/