控制台.log与返回:不同的结果 (JS)



我不明白为什么下面的代码在filter函数内部和return函数中的console.log中给出不同的结果:

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' ]

编辑: 显然,我还不够清楚。简单来说,为什么我在控制台中得到 400.log在过滤器中得到 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 值的原因。

如果你想要输出,你可以试试下面的代码 [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);

num.split('')返回一个数组['2', '0', '4']

num.split('').filter(function(){ return handler()})hander() is true时返回元素,则第二个参数是 '0',它的最终结果是 0,所以它不会保留这个元素。

从表面上讲,重用是['2', '4']

正如 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. 

您需要阅读.filter functionhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter 的文档

包含通过测试的元素的新数组。如果没有元素通过 测试,将返回一个空数组。

不管你从过滤器函数内部返回什么,它只关心每个索引是否为 false。由于您在 402 中有 0,它会跳过中间元素并仅返回>0 的元素

最新更新