简体   繁体   English

JavaScript中的“=>”运算符

[英]“=>” operator in JavaScript

I mixed up Ruby with JavaScript syntax when trying to declare an associative array in JavaScript . 尝试在JavaScript中声明关联数组时,我将RubyJavaScript语法混合在一起。

>>> [a => b, c => d]

This results in a valid array and 这会产生一个有效的数组和

>>> JSON.stringify([a => b, c => d])

returns "[null,null]" and 返回"[null,null]"

typeof(a) === "undefined" // true
typeof(b) === "undefined" // true
typeof(c) === "undefined" // true
typeof(d) === "undefined" // true

What does this syntax mean? 这个语法是什么意思?

That's the syntax for ES6's arrow function , which is both a shorthand and sets the values of this lexically. 这对语法ES6的箭头作用 ,这既是一种速记和设置的值, this词汇。 It uses the following syntax: 它使用以下语法:

argument => returnValue

It can also be used with multiple arguments or with a function body (which makes a return statement needed for a non-void function): 它也可以与多个参数一起使用或与函数体一起使用(这使得非void函数需要return语句):

() => 1
(arg1, arg2) => 2
argument => { return 3; }

The return value is implicit, which is why it appears to work. 返回值是隐式的,这就是它似乎工作的原因。 While this is still experimental, Firefox has implemented this, though other browsers have not yet done so. 虽然这仍然是实验性的,但Firefox已经实现了这一点,尽管其他浏览器还没有这样做。

The reason why you're getting "[null]" is that functions cannot be represented in JSON, so they are converted to null for serialisation purposes. 你得到"[null]"是函数不能用JSON表示,所以为了序列化目的它们被转换为null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM