gpt4 book ai didi

javascript - 不带引号的 JavaScript 对象文字键的规则?

转载 作者:可可西里 更新时间:2023-11-01 01:47:15 24 4
gpt4 key购买 nike

在 JavaScript 中,你可以这样定义一个对象:

var d = {1: 'test'};

我可以像这样设置一个带有负数索引的键:

d[-1] = 'test2';

但是如果我尝试在文字初始化中使用负数,则会出现错误:

var d = {1: 'test', -1: 'test2'};
Uncaught SyntaxError: Unexpected token -

这是为什么?为什么我不能使用文字负数作为对象的键?有没有一种解决方法可以让我将其初始化为文字。我知道我可以改用字符串,但我想使用整数。

最佳答案

来自 Unquoted property names / object keys in JavaScript ,我关于这个主题的文章:

Quotes can only be omitted if the property name is a numeric literal or a valid identifier name.

[…]

Bracket notation can safely be used for all property names.

[…]

Dot notation can only be used when the property name is a valid identifier name.

-1 不是数字文字,它是一元 - 运算符后跟数字文字 (1)。

我还制作了一个工具,可以告诉您任何给定的属性名称是否可以不带引号和/或点符号使用。在 mothereff.in/js-properties 试试.

Screenshot

关于javascript - 不带引号的 JavaScript 对象文字键的规则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9367572/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com