Javascript 使用箭头函数循环遍历值数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33763768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:27:16  来源:igfitidea点击:

Loop through array of values with Arrow Function

javascriptecmascript-6

提问by PositiveGuy

Lets say I have:

可以说我有:

var someValues = [1, 'abc', 3, 'sss'];

How can I use an arrow function to loop through each and perform an operation on each value?

如何使用箭头函数循环遍历每个值并对每个值执行操作?

回答by Long Nguyen

In short:

简而言之:

someValues.forEach((element) => {
    console.log(element);
});

If you care about index, then second parameter can be passed to receive the index of current element:

如果你关心索引,那么可以传递第二个参数来接收当前元素的索引:

someValues.forEach((element, index) => {
    console.log(`Current index: ${index}`);
    console.log(element);
});

Refer here to know more about Array of ES6: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

请参阅此处了解有关 ES6 数组的更多信息:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

回答by monnef

One statement can be written as such:

一个语句可以写成这样:

someValues.forEach(x => console.log(x));

or multiple statements can be enclosed in {}like this:

或者多个语句可以{}像这样包含在:

someValues.forEach(x => { let a = 2 + x; console.log(a); });