如何从forEach javascript中获取值



我一直使用array.forEach(element=>console.log(element)来查看我从数组中获得的内容;但现在我想获得价值本身。

假设我有以下代码:

array=['1','2','3','4']
array.forEach(x=>x)//undefined

我想要获得的是:

'1'
'2'
'3'
'4'

这是正确的方法吗?还是还有其他我现在看不到的方法?

array.forEach()每次向回调显示一个值。这就是它的工作方式,为了使用它,您将代码放入回调中,对值执行某些操作。

例如:

let array = [1,2,3,4];
let product = 1;
array.forEach(x => {
console.log(x);
// update the product variable
product *= x;
});
console.log(product);

如果您试图在控制台中执行array.forEach(x, ...),那么您会看到undefined,因为array.forEach()没有返回值(因此undefined也没有返回值(。


.map().filter().reduce()等其他数组函数都有返回值,您可以根据要对数组执行的操作类型选择其中一个。

例如,以前的代码块,可能是用.reduce()编写的

let array = [1,2,3,4];
let product = array.reduce((total, x) => {
console.log(x);
return total * x;
}, 1);
console.log(product);


这里有一个.map()的例子,它返回一个每个值平方的新数组:

let array = [1,2,3,4];
let product = array.map(x => {
return x ** 2;
}, 1);
console.log(product);

最新更新