JavaScript 中的“=>”是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38405369/
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
What does "=>" mean in JavaScript?
提问by Twigs
Here is the code:
这是代码:
function accum(s) {
return s.split('').map((x,index) => x.toUpperCase()+Array(index+1).join(x.toLowerCase())).join('-');
}
I would like to know what "=>" is. This function takes a string and for the index number of each element it adds that many elements to the output. Here's an example:
我想知道“=>”是什么。此函数接受一个字符串,并为每个元素的索引号添加许多元素到输出中。下面是一个例子:
accum("abcd") --> "A-Bb-Ccc-Dddd"
accum("RqaEzty") --> "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy"
accum("cwAt") --> "C-Ww-Aaa-Tttt"
采纳答案by Christos
It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.
这是 ES6 中引入的一个新特性,称为箭头函数。左侧部分表示函数的输入,右侧部分表示该函数的输出。
So in your case
所以在你的情况下
s.split('')
splits the input on empty spaces and for each element of the resulted array you apply the following function:
在空白处拆分输入,对于结果数组的每个元素,您应用以下函数:
(x,index) => x.toUpperCase()+Array(index+1).join(x.toLowerCase())
The left part is the random element, x
of the array (s.split('')
) and it's corresponding index. The second part applies a transformation to this input.
左侧部分是x
数组 ( s.split('')
)的随机元素及其对应的索引。第二部分对此输入应用转换。