使用构造函数的javascript中的程序

时间:2016-07-31 02:35:05

标签: javascript multidimensional-array constructor dynamic-arrays

<script>

<!-- A program to search for a friend from an object -->

var friends = {
    bill: {
        firstName: "Bill",
        lastName: "Gates",
        number: "205-555-1111",
        address:["One Microsoft Day","Redmond","WA","90852"]
    },

    steve: {
        firstName: "Steve",
        lastName: "Jobs",
        number: "408-555-2222",
        address: ["One Infinite Loop", "Cupertino", "CA", "95014"]
    },

    wendy: {
        firstName: "Wendy",
        lastName: "Johnson",
        number: "510-555-3333",
        address: ["3555 Anyplace drive","New York", "NY","11001"]
    }

}

    alert(friends["steve"].lastName);

    alert(friends.length);

    var search = function(name)
        {
            document.write(name);
            for (var nameSearch in friends)
                {
                    alert(nameSearch.firstName);
                    if(friends[nameSearch].firstName===name)
                        {
                            return friends[nameSearch];
                        }
                }
        }

    search("Wendy");

</script>

1 个答案:

答案 0 :(得分:0)

你的代码有几个问题:

  • 对象没有长度属性,因此friends.length的第二个警报无法正常工作
  • 当您使用for in时,您正在引用该对象的键,因此在这种情况下,它将是billstevewendy所以当您执行nameSearch.firstName它将是未定义的,因为nameSearch是一个字符串
  • 最后,您的示例失败的原因是您正在搜索区分大小写的文本。 wendy!= Wendy。另请注意,三等于检查构造函数。

要修复代码,您可以尝试降低所有搜索文本的大小:

var friends = {
    bill: {
        firstName: "Bill",
        lastName: "Gates",
        number: "205-555-1111",
        address:["One Microsoft Day","Redmond","WA","90852"]
    },

    steve: {
        firstName: "Steve",
        lastName: "Jobs",
        number: "408-555-2222",
        address: ["One Infinite Loop", "Cupertino", "CA", "95014"]
    },

    wendy: {
        firstName: "Wendy",
        lastName: "Johnson",
        number: "510-555-3333",
        address: ["3555 Anyplace drive","New York", "NY","11001"]
    }

};

var search = function(name) {
  for (var nameSearch in friends) {
    if(friends[nameSearch].firstName.toLowerCase()===name.toLowerCase()) {
      return friends[nameSearch];
    }
  }
}

console.log(search("wendy"));