Javascript ES6 箭头函数和 array.map
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48682468/
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
ES6 arrow functions and array.map
提问by Kermit
I am trying to understand some shorthand ways of writing ES6. What I cannot fully understand in the example below is the last shorthand "({length})" - I comprehend that it does work, and that it gets the length property of the array, but not why. How could this syntax be applied in another scenario, not involving arrays?
我试图了解一些编写 ES6 的速记方式。在下面的示例中我无法完全理解的是最后一个速记“({length})”——我理解它确实有效,并且它获得了数组的长度属性,但不知道为什么。这种语法如何应用于另一种不涉及数组的场景?
//Declare array
var materials = [
'Hydrogen',
'Helium',
'Lithium',
'Beryllium'
];
//Long version - ok
materials.map(function(material) {
return material.length;
});
//Arrow function - ok
materials.map((material) => {
return material.length;
});
//Shorthand arrow function - ok
materials.map(str => str.length);
//What? :)
materials.map(({length}) => length));
The example above is from the mozilla documentation of arrow functions. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
上面的例子来自箭头函数的 mozilla 文档。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
回答by Ori Drori
The lengthis a property of strings, and can be destructuredand returned in the map.
该length是一个字符串属性,可以解构,并在地图上返回。
It's mostly the same as:
它主要与以下内容相同:
materials.map((str) => {
const {length} = str;
return length;
});

