我想在 JavaScript 中从这个散列中获取一个值:
hash= {:user_authenticated=>false, :user_email=>"nope"}
hash.user_authenticated
hash[user_authenticated]
hash["user_authenticated"]
hash[:user_authenticated]
似乎没有任何效果。我收到此错误:
语法错误:无效的属性 ID
最佳答案
Javascript 对象不能像 Ruby 的哈希那样用火箭语法表示。
然而,随着 ECMAScript 6 的采用,Javascript 实现已经能够使用相同的符号,=>
用于匿名函数定义,尽管它们被称为箭头函数或通俗地称为粗箭头而不是哈希火箭。
对于简单的函数,用箭头语法定义和传统函数没有区别。
var foo = function (s) { return s.toString() }
和
function foo(s) { return s.toString() }
相当于:
var foo = (s) => { return s.toString() }
此外,这些都等同于:
var foo = (s) => s.toString()
还有:
const foo = s => s.toString()
然而,当使用 this
时,传统函数和箭头函数之间的选择很重要,因为传统定义的函数会为 this
创建一个新的作用域,而箭头函数则不会。来自 the Mozilla doc on Arrow functions 的示例通过 Mozilla Contributors (根据 CC-BY-SA 2.5 获得许可):
function Person() {
// The Person() constructor defines `this` as an instance of itself.
this.age = 0;
setInterval(function growUp() {
// In non-strict mode, the growUp() function defines `this`
// as the global object, which is different from the `this`
// defined by the Person() constructor.
this.age++;
}, 1000);
}
var p = new Person();
这里,p.age
将始终为 0,因为递增的 age
属于仅存在于内部函数中的 this
,而不是 Person
的实例,它是 p
。当内部函数定义为箭头函数时:
function Person() {
// The Person() constructor defines `this` as an instance of itself.
this.age = 0;
setInterval(() => {
// In non-strict mode, the growUp() function defines `this`
// as the global object, which is different from the `this`
// defined by the Person() constructor.
this.age++;
}, 1000);
}
var p = new Person();
p.age
将等于自 p
创建以来的秒数,因为内部函数中的 this
是实例的 这个
。
更多信息请引用Mozilla docs .
关于火箭语法中的javascript对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24945537/