未捕获的SyntaxError:意外的数字对象

时间:2018-03-09 11:10:42

标签: javascript

var s = '{"1" : "Sammy", "2" : "Shark", "3" : "Ocean"}';

var obj = JSON.parse(s);

document.getElementById("user").innerHTML =
"Name: " + obj.1 + " " + obj.2 + "<br>" +
"Location: " + obj.3;

控制台出错:

Uncaught SyntaxError: Unexpected number

3 个答案:

答案 0 :(得分:4)

使用括号表示法访问对象的数字键:

&#13;
&#13;
const obj = { "1": "Sammy" };
console.log(obj["1"]);
&#13;
&#13;
&#13;

使用其他字符也是如此,例如-

&#13;
&#13;
const obj = { "test-123": "works only with bracket notation" };
console.log(obj["test-123"]);
&#13;
&#13;
&#13;

正如gurvinder372所示,标识符不能是数字,您尝试使用数字访问对象的属性,这是错误的。

答案 1 :(得分:0)

更正代码

var s = JSON.parse('{"1" : "Sammy", "2" : "Shark", "3" : "Ocean"}');

document.getElementById("user").innerHTML =
"Name: " + s["1"] + " " + s["2"] + "<br>" +
"Location: " + s["3"];

答案 2 :(得分:0)

之后你不能拥有数字。 (点运算符) 你应该尝试使用[]。

var s = '{"1" : "Sammy", "2" : "Shark", "3" : "Ocean"}';

var obj = JSON.parse(s);

document.getElementById("user").innerHTML =
"Name: " + obj[1] + " " + obj[2] + "<br>" +
"Location: " + obj[3];