<html>
<head>
<script>
function User(name,age){
this.name=name;
this.age=age;
}
var user = new User('Daniel', 45 );
document.write(user[name]+' '+'is'+' '); //line 1
document.write(user[age]+' '+'years old!'); // line 2
</script>
</head>
<body>
</body>
</html>
在上面的代码中,
当我尝试访问对象用户的属性时
为了名字,我得到“未定义”作为输出
对于年龄,我收到错误消息,指出年龄未定义
无法理解为什么第二行出现错误
和第1行的'undefined'值。两者都应赋予相同的错误权?
请在这里澄清我的疑问。
最佳答案
因为访问错误。 user[name]
不是访问对象属性的正确语法。
应该:
user['name']
甚至更简单:
user.name
进一步阅读有关访问对象属性的信息:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors
关于javascript - 访问对象属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44925514/