为什么与值完全相同的变量不能代替它

Why can't a variable that is literally identical to a value work in its place?

本文关键字:不能 变量 为什么      更新时间:2023-09-26

所以这段代码旨在获取一个数组(由某人的联系人列表中的不同人员表示(,并使用带有两个参数(一个人的名字和一个属性,均由用户提供(的 lookUp 函数来确定:

  1. 此人是否确实在您的联系人列表中
  2. 该属性是否实际存在于该人员的单个数组中
  3. 如果两个值都返回 true,则打印提供的属性的值

     function lookUp(firstName, prop){
       var i;
       var newArray = [];
    for (i = 0; i < contacts.length; i++) {
       var fn = contacts[i].firstName;
       newArray.push(fn);
    }
    var foundName = $.inArray(arguments[0], newArray) > -1;
    if (foundName === true){
       var place = $.inArray(arguments[0], newArray);
       var property = arguments[1];
          if (property == "likes"){
       return contacts[place].likes;
           } else if (property == "number"){
       return contacts[place].number;
           } else if (property == "lastName"){
       return contacts[place].lastName;
           } else {
          return "No such property";
       }
       } else {
       return "No such contact";
       }
    

为了方便起见,还有一个示例数组:

       var contacts = [
       {
       "firstName": "Akira",
       "lastName": "Laine",
       "number": "0543236543",
       "likes": ["Pizza", "Coding", "Brownie Points"]
       },
       {
       "firstName": "Harry",
       "lastName": "Potter",
       "number": "0994372684",
       "likes": ["Hogwarts", "Magic", "Hagrid"]
       },

现在该函数按原样工作正常,但在我以前的版本中,我有这个来输出现有联系人的属性:

       var foundName = $.inArray(arguments[0], newArray) > -1;
       if (foundName === true){
       var place = $.inArray(arguments[0], newArray);
       var property = arguments[1];
       return contacts[place].property;
       } else {
       return "No such contact";
       }

而不是我的新代码的修订"解决方法",这是:

       var foundName = $.inArray(arguments[0], newArray) > -1;
       if (foundName === true){
       var place = $.inArray(arguments[0], newArray);
       var property = arguments[1];
          if (property == "likes"){
       return contacts[place].likes;
           } else if (property == "number"){
       return contacts[place].number;
           } else if (property == "lastName"){
       return contacts[place].lastName;
           } else {
          return "No such property";
       }
       } else {
       return "No such contact";
       }

对于以前版本的代码,即使 var 属性等于 "likes",也不会返回任何内容;contacts[place].likes 将返回喜欢的列表,但 contacts[place].property 根本不返回任何内容。 因此,我的解决方法代码,其中我只是逐个获取每个属性以查看它是否存在。为什么会这样? 为什么变量(字面意思完全相同(不能代替所讨论的属性,并达到相同的结果?

简短的回答:语法。

更长的答案:

在像 foo.bar 这样的表达式中,标记foo是引用对象的变量的名称。 令牌bar是该对象的属性的名称。 bar不是变量名。 这是语言的定义。

相反,在像 foo[bar] 这样的表达式中,标记foo仍然是引用对象的变量的名称。 但是,令牌bar ,现在也是引用值(通常是字符串或整数(的变量的名称,该值是属性的名称。

您需要使用括号表示法访问该属性。我会这样写...

var place = $.inArray( firstname , newArray);
if ( place > -1 ){
    return contacts[ place ][ prop ];
} 
else {
    return "No such contact";
}