不带引号的JavaScript对象文字键的规则? [英] Rules for unquoted JavaScript Object Literal Keys?

查看:107
本文介绍了不带引号的JavaScript对象文字键的规则?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  var d = {1:'test'}; 

我可以设置一个带负数索引的密钥,如下所示:

  d [-1] ='test2'; 

但如果我尝试在文字初始化中使用负数,我会收到错误:

  var d = {1:'test', -  1:'test2'}; 
未捕获的SyntaxError:意外的令牌 -

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

解决方案

来自


In JavaScript, you can define an object like this:

var d = {1: 'test'};

and I can set a key with a negative number index like this:

d[-1] = 'test2';

but if I try to use a negative number in the literal initialization, I get an error:

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

Why is this? Why can't I use a literal negative number as a key to an object? Is there a workaround that allows me to initialize it as a literal. I know I could use strings instead, but I want to use integers.

解决方案

From Unquoted property names / object keys in JavaScript, my write-up on the subject:

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 is not a numeric literal, it’s a unary - operator followed by a numeric literal (1).

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.

这篇关于不带引号的JavaScript对象文字键的规则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆