有效的javascript对象属性名称 [英] Valid javascript object property names

查看:113
本文介绍了有效的javascript对象属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找出对javascript对象的属性名称有效的内容。例如

I'm trying to work out what is considered valid for the property name of a javascript object. For example

var b = {}
b['-^colour'] = "blue";     // Works fine in Firefox, Chrome, Safari
b['colour'] = "green";      // Ditto
alert(b['-^colour']);       // Ditto
alert(b.colour);            // Ditto
for(prop in b) alert(prop); // Ditto
//alert(b.-^colour);     // Fails (expected)

post 详细说明有效的javascript变量名称,' - ^ color'显然无效(作为变量名)。这同样适用于对象属性名称吗?看看上面的内容我试图解决如果

This post details valid javascript variable names, and '-^colour' is clearly not valid (as a variable name). Does the same apply to object property names? Looking at the above I'm trying to work out if


  1. b [' - ^ color']无效,但是有效在quirk的所有浏览器中,我不应该相信它可以继续工作

  1. b['-^colour'] is invalid, but works in all browsers by quirk, and I shouldn't trust it to work going forward

b [' - ^ color']完全有效,但它只是一个只能以这种方式访问​​的表单 - (它支持所以对象可以用作地图吗?)

b['-^colour'] is completely valid, but it's just of a form that can only be accessed in this manner - (it's supported so Objects can be used as maps perhaps?)

其他东西

顺便说一句,javascript中的全局变量可能会在顶级声明为

As an aside, a global variable in javascript might be declared at the top level as

var abc = 0;

但也可以用

window['abc'] = 0;

以下适用于以上所有浏览器

the following works in all the above browsers

window['@£$%'] = "bling!";
alert(window['@£$%']);

这有效吗?它似乎与变量命名规则相矛盾 - 或者我不是在那里声明变量?变量和对象属性名称之间有什么区别?

Is this valid? It seems to contradict the variable naming rules - or am I not declaring a variable there? What's the difference between a variable and an object property name?

推荐答案

是的,对象可以用作地图,任何字符串都可以是一个属性名称。正如您所发现的,某些属性只能使用括号语法访问

Yes, objects can be used as maps, and any string can be a property name. As you've discovered, some properties can only be accessed using the bracket syntax.

window['abc']

正在访问一个属性。它不是变量,即使它引用相同的值(在全局级别):

is accessing a property. It is not a variable, even though it refers to the same value (at the global level) as:

abc

这篇关于有效的javascript对象属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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