Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
537 views
in Technique[技术] by (71.8m points)

key - Can I get a javascript object property name that starts with a number?

var myObj = {"suppliers":[{"name":"supplier1","12m":"0.08","24m":"0.06"}]};

alert(myObj.suppliers[0].12m);

Is there a different way to get this property, or should I just not use a key that starts with a number?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use the following syntax to do what you describe using bracket notation:

myObject["myProperty"]

Bracket notation differs from dot notation (e.g. myObject.myProperty) in that it can be used to access properties whose names are illegal. Illegal meaning that with dot notation, you're limited to using property names that are alphanumeric (plus the underscore _ and dollar sign $), and don't begin with a number. Bracket notation allows us to use a string to access a property and bypass this.

myObject.1 // fails, properties cannot begin with numbers
myObject.& // fails, properties must be alphanumeric (or $ or _)

myObject["1"] // succeeds
myObject["&"] // succeeds

This also means we can use string variables to look up and set properties on objects:

var myEdgyPropertyName = "||~~(_o__o_)~~||";

myEdgyObject[myEdgyPropertyName] = "who's there?";

myEdgyObject[myEdgyPropertyName] // "who's there?";

You can read more about dot and bracket notation here, on MDN.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...