我有一个对象,其中一个属性以数字开头。我已经知道这是允许的,但我收到了这个错误:
SyntaxError:标识符在数字文字
之后立即开始
var stats = {"LOAD_AVG":{"1_MIN":0.08,"5_MIN":0.08,"15_MIN":0.08},"COUNTS":{"TOTAL":888,"RUNNING":1,"SLEEPING":887,"STOPPED":0,"ZOMBIE":0},"CPU":{"USER_CPU_TIME":8.9,"SYSTEM_CPU_TIME":2.4,"NICE_CPU_TIME":0,"IO_WAIT_TIME":1,"HARD_TIME":0,"SOFT_TIME":0.1,"STEAL_TIME":0},"MEMORY":{"PHYSICAL":{"TOTAL":"3921.98mb","IN_USE":"3682.652mb (93.9%)","AVAILABLE":"239.328mb (6.1%)","BUFFERS":"266.492mb (6.8%)"},"SWAP":{"TOTAL":"4194.296mb","IN_USE":"64.264mb (1.5%)","AVAILABLE":"4130.032mb (98.5%)","CACHE":"1191.328mb (28.4%)"}}};
//works fine
window.alert(stats.COUNTS.TOTAL);
//doesn't work
window.alert(stats.LOAD_AVG.1_MIN);
如何在不重写生成数字的PHP的情况下访问以数字开头的属性?
答案 0 :(得分:2)
您可以将bracket access用于无效JavaScript标识符的属性,该属性用于包含空格的属性名称或其他语言符号,例如+
,*
window.alert(stats.LOAD_AVG["1_MIN"]);
您可以在任何地方使用括号访问
window.alert(stats["COUNTS"]["TOTAL"]);