“密钥”的类型是什么?在 JavaScript 中?
当我失去焦点并开始思考一个愚蠢的问题时,我遇到了这样的时刻:
var a = {
b: "value"
}
“b”的类型是什么,我的意思不是“值”的类型,而是标记为 b 的实际键?
背景: 当我必须创建一个字符串键时,我开始想知道这一点:
var a = {
"b": "value"
}
因为后来它被引用为:
a["b"]
然后最终想知道原来的问题。
I bumbed into one of those moments when I just lose the focus and start wondering on a silly question:
var a = {
b: "value"
}
What is the typeof 'b' and I don't mean the typeof "value", but the actual Key labeled as b?
background:
I started wondering about this when I had to create a key which is a string:
var a = {
"b": "value"
}
because at a later point it is referenced as:
a["b"]
And then ended up wondering about the original question.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
用对象字面量来说,
b
是一个属性。属性可以是 JavaScript 中的字符串或 符号,尽管在对象文字中定义属性名称时,您可以省略字符串分隔符。In object literal terms,
b
is a property. Properties are either strings or symbols in JavaScript, although when defining the property name inside an object literal you may omit the string delimiters.属性名称会自动强制转换为字符串。您可以通过使用数字文字作为属性名称来尝试此操作。
因此,我建议仅使用字符串文字作为属性名称。
来自 JavaScript 中不带引号的属性名称/对象键,我关于这个主题的文章:
我还制作了一个工具,它会告诉您是否可以使用任何给定的属性名称而不使用引号和/或点符号。请访问 mothereff.in/js-properties 尝试一下。
Property names are automatically coerced into a string. You can try this yourself by using a numeric literal as a property name.
For this reason, I’d recommend using only string literals for property names.
From Unquoted property names / object keys in JavaScript, my write-up on the subject:
I also made a tool that will tell you if any given property name can be used without quotes and/or with dot notation. Try it at mothereff.in/js-properties.
b 是一个字符串,它只是一个简写语法,所以你写
而不是
b is a string, it's just a shorthand syntax, so you write
instead of
请记住,JavaScript 对象是哈希表,键只是字符串。您可以在声明期间省略属性名称周围的引号,但如果您对属性名称或任何其他恰好是无效标识符的名称使用保留字,例如以数字开头或包含空格,则必须将属性包装起来引号中的名称:
另请注意,您可以使用点符号或下标符号引用对象的属性,无论声明时是否使用引号。但是,如果您使用的属性名称是无效标识符,例如上面示例中的属性名称,则必须使用下标表示法:
Keep in mind that JavaScript objects are hash tables and the keys are just strings. You may omit the quotes around property names during declaration, but if you use reserved words for property names or any other name that happens to be an invalid identifier, such as starting with a digit, or containing spaces, you would have to wrap the property names in quotes:
Also note that you can reference the properties of objects using the dot notation or the subscript notation regardless of whether quotes were used when they were declared. However, if you use property names that would be invalid identifiers, such as the ones in the above example, you are forced to use the subscript notation:
javascript 对象中的键可以是字符串和符号。符号是JavaScript中的一种原始数据类型。
Keys in javascript objects can be strings and symbols. symbol is a primitive data type in javascript.