简体   繁体   English

在数组的控制台对象中打印

[英]Printing in the console objects of an array

Hi I have been trying to learn Javascript using codeacademy.com and I have reached an exercise that doesn't seem to make any sense when why the exercise I have written.This is my code:嗨,我一直在尝试使用 codeacademy.com 来学习 Javascript,我已经完成了一个练习,但我写这个练习的原因似乎没有任何意义。这是我的代码:

 (function(){
    var bob = {
        firstName: "Bob",
        lastName: "Jones",

        phoneNumber: "(650) 777 - 7777",
        email: "bob.jones@example.com"
    };

    var mary = {
        firstName: "Mary",
        lastName: "Johnson",

        phoneNumber: "(650) 888 - 8888",
        email: "mary.johnson@example.com"
    };

    var contacts = [bob, mary];

    var printPerson = function(person){
        console.log(person.firstName + " " + person.lastName);
    }

    var list = function(){
        var i = contacts.length;
        for(var j= 0; j < i ; j++){
            printPerson(contacts[i]);
        }
    };

        list();
})();

The problem is in the list function when I try to call the printPerson() function I get that person is undefined but if I write instead of the list() function this:问题出在列表 function 中,当我尝试调用 printPerson() function 时,我得到那个人是未定义的,但是如果我写而不是列表() function 是这样的:

    printPerson(contacts[0]);
    printPerson(contacts[1]);

Everything works.What am I doing wrong in the list() function that it doesn't work?一切正常。我在 list() function 中做错了什么,它不起作用?

var list = function(){
    var i = contacts.length;
    for(var j= 0; j < i ; j++){
        printPerson(contacts[i]);
    }
};

i here is a constant. i在这里是一个常数。 If you replace it:如果你更换它:

var list = function(){
    var i = contacts.length;
    for(var j= 0; j < contacts.length ; j++){
        printPerson(contacts[contacts.length]);
    }
};

For all arrays arr , arr[arr.length] will always be undefined.对于所有 arrays arrarr[arr.length]将始终未定义。 You probably want contacts[j] .你可能想要contacts[j]

for(var j= 0; j < i ; j++){
    printPerson(contacts[i]); // this should be contacts[j]
}
contacts.forEach(function(contact) {
    printPerson(contact);
});
var bob = {
    firstName: "Bob",
    lastName: "Jones",
    phoneNumber: "(650) 777-7777",
    email: "bob.jones@example.com"
};

var mary = {
    firstName: "mary",
    lastName: "Johnson",
    phoneNumber: "(650) 888 - 8888",
    email: "mary.johnson@example.com"
};


 var contacts=[bob,mary];
 console.log(mary.phoneNumber);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM