为什么if语句不接受括号表示而不是点符号?

时间:2016-09-26 05:33:27

标签: javascript-objects

var contacts = [
{
    "firstName": "Akira",
    "lastName": "Laine",
    "number": "0543236543",
    "likes": ["Pizza", "Coding", "Brownie Points"]
},
{
    "firstName": "Harry",
    "lastName": "Potter",
    "number": "0994372684",
    "likes": ["Hogwarts", "Magic", "Hagrid"]
},
{
    "firstName": "Sherlock",
    "lastName": "Holmes",
    "number": "0487345643",
    "likes": ["Intriguing Cases", "Violin"]
},
{
    "firstName": "Kristian",
    "lastName": "Vos",
    "number": "unknown",
    "likes": ["Javascript", "Gaming", "Foxes"]
}];
function lookUpProfile(firstName, prop){
for (var i = 0; i < contacts.length; i++){
if (firstName === contacts[i].firstName) {
if (contacts[i][prop]) {
    return contacts[i][prop];
} else {
    return "No such property";
  }
}
}
return "No such contact"; 
}
lookUpProfile("Akira", "likes");

此代码运行完美。但如果我使用if(firstName === contacts [i] [firstName])而不是if(firstName === contacts [i] .firstName),则它不起作用。为什么?由于点或括号表示法都可用于访问对象属性。

1 个答案:

答案 0 :(得分:0)

括号用于变量。如果你想使用String文字,你可以,但你必须引用它们:contacts[i]['firstName']。但除非属性名称包含受限制的字符(例如另一个点或空格),否则这只是愚蠢的。

请注意,您已使用i(这是一个变量)来获取i个元素(而不是名为i的属性)。