无法使用索引从我的数组调用项目-Javascript

时间:2018-10-03 20:35:44

标签: javascript

所以我得到了这段代码,该代码可以将API中的数据推送到数组中,并且可以正常工作。 如果我将整个数组记录下来,它的确会显示整个数组,但是,如果我尝试记录数组中的特定对象,它将返回“未定义”。

我的代码如下:

let people = [];
fetch('https://randomuser.me/api/?results=10')
    .then(function(response){
        return response.json();
    })
    .then(function(data){
        for(i=0; i<10; i++){
            let person = data.results[i];
            let x = {
                name: person.name.first + " " +person.name.last,
                picture: person.picture.large,
                age: person.dob.age,
                place: person.location.street + "<br>" + person.location.city + "<br>" + person.location.state
            }
            people.push(x);
        }
    }).catch(function(error){
            console.log('Data is not shown ' + error.message);
});


console.log(people); // works fine
console.log(people[0]); // returns undefined
console.log(people.length); //returns 0

3 个答案:

答案 0 :(得分:0)

@ibrahimyilmaz是正确的:您想控制台日志在您的AJAX请求完成后,使用people数组

如何处理阵列取决于您自己。假设您有一个将person的名称插入DOM的函数:

function renderPersonsNameToHeader(person) {
    var header = document.querySelector('h1');
    header.innerText = person.name;
}

所以您的代码如下:

let people = [];

function renderPersonsNameToHeader(person) {
    var header = document.querySelector('h1');
    header.innerText = person.name;
}

fetch('https://randomuser.me/api/?results=10')
    .then(function(response){
        return response.json();
    })
    .then(function(data){
        for(i=0; i<10; i++){
            let person = data.results[i];
            let x = {
                name: person.name.first + " " +person.name.last,
                picture: person.picture.large,
                age: person.dob.age,
                place: person.location.street + "<br>" + person.location.city + "<br>" + person.location.state
            }
            people.push(x);
        }

        // Now that our `people` array is built, we can use the data!
        renderPersonsNameToHeader(people[0]);
    }).catch(function(error){
        onsole.log('Data is not shown ' + error.message);
    });

答案 1 :(得分:0)

React.PureComponent

答案 2 :(得分:0)

let people = [];
fetch('https://randomuser.me/api/?results=10')
.then(function(response){
    return response.json();
})
.then(function(data){
    for(i=0; i<10; i++){
        let person = data.results[i];
        let x = {
            name: person.name.first + " " +person.name.last,
            picture: person.picture.large,
            age: person.dob.age,
            place: person.location.street + "<br>" +      person.location.city + "<br>" + person.location.state
        }
addPerson(people,x);
      }
function addPerson(array,value){
array.push(value);
}
// Run these _after_ your `for` loop
    console.log(people);
    console.log(people[0]);
    console.log(people.length);
}).catch(function(error){
    onsole.log('Data is not shown ' + error.message);
});