gpt4 book ai didi

javascript - 对象属性未定义,但对象本身显示了所有数据

转载 作者:太空宇宙 更新时间:2023-11-04 15:59:36 25 4
gpt4 key购买 nike

我正在为一个小型项目构建一个单页应用程序。我一直在尝试将 API 调用中的数据保存到对象中的电影数据库中。如果我 console.log 该对象,我可以看到它的所有属性和值。如果我 console.log object.property,它会返回“未定义”。这是代码:

(() => {
"use strict"

/* Saving sections to variables
--------------------------------------------------------------*/
const movieList = document.getElementsByClassName('movie_list')[0];
const movieSingle = document.getElementsByClassName('movie_single')[0];

/* All standard filters for displaying movies
--------------------------------------------------------------*/
const allFilters = {
trending: 'movie/popular',
toplist: 'movie/top_rated',
latest: 'movie/now_playing',
upcoming: 'movie/upcoming'
};

const allData = {};

/* Initialize app - Get al standard data and save it in object
--------------------------------------------------------------*/
const app = {
init() {
getData(allFilters.trending, 'popular');
getData(allFilters.toplist, 'toplist');
getData(allFilters.latest, 'latest');
getData(allFilters.upcoming, 'upcoming');

this.startPage();
},
startPage() {
window.location.hash = "trending";
}
}

/* Function for getting data from the API
--------------------------------------------------------------*/
const getData = (filter, key) => {
const request = new XMLHttpRequest();
const apiKey = '?api_key=xxx';
const getUrl = `https://api.themoviedb.org/3/${filter}${apiKey}`;

request.open('GET', getUrl, true);
request.onload = () => {
if (request.status >= 200 && request.status < 400) {
let data = JSON.parse(request.responseText);
data.filter = key;
cleanData.init(data);
} else {
window.location.hash = 'random';
}
};
request.onerror = () => {
console.error('Error');
};
request.send();
};

/* Check if the data is list or single, and clean up
--------------------------------------------------------------*/
const cleanData = {
init(originalData) {
if (!originalData.results) {
this.single(originalData);
} else {
allData[originalData.filter] = originalData;
}
},

list(data) {
data.results.map(function(el) {
el.backdrop_path = `https://image.tmdb.org/t/p/w500/${el.backdrop_path}`;
});
let attributes = {
movie_image: {
src: function() {
return this.backdrop_path;
},
alt: function() {
return this.title;
}
},
title_url: {
href: function() {
return `#movie/${this.id}/${this.title}`;
}
}
}
showList(data.results, attributes);
},

single(data) {
data.poster_path = `https://image.tmdb.org/t/p/w500/${data.poster_path}`;
data.budget = formatCurrency(data.budget);
data.revenue = formatCurrency(data.revenue);
data.runtime = `${(data.runtime / 60).toFixed(1)} uur`;
data.imdb_id = `http://www.imdb.com/title/${data.imdb_id}`;
let attributes = {
movie_image: {
src: function() {
return this.poster_path;
},
alt: function() {
return this.title;
}
},
imdb_url: {
href: function() {
return this.imdb_id
}
},
similar_url: {
href: function() {
return `#movie/${this.id}/${this.title}/similar`
}
}
};
showSingle(data, attributes);
}
};

const showList = (cleanedData, attributes) => {
movieList.classList.remove('hidden');
movieSingle.classList.add('hidden');
Transparency.render(movieList, cleanedData, attributes);
};

const showSingle = (cleanedData, attributes) => {
movieSingle.classList.remove('hidden');
movieList.classList.add('hidden');
Transparency.render(movieSingle, cleanedData, attributes);
}

const formatCurrency = amount => {
amount = amount.toFixed(0).replace(/./g, function(c, i, a) {
return i && c !== "." && ((a.length - i) % 3 === 0) ? '.' + c : c;
});
return `€${amount},-`;
};

app.init();

console.log(allData); // Returns object with 4 properties: trending, toplist, latest & upcoming. Each property is filled with 20 results (movies with data) from the API.

console.log(allData.trending) // Returns 'undefined' (each property I've tried).

console.log(allData['trending']) // Returns 'undefined'

Object.keys(allData); // Returns an empty Array []

})();

当我使用 console.log(allData) 时,我看到 4 个属性,全部填充了 API 的结果。但是,当我执行 console.log(allData.trending)console.log(allData['trending']) 时,它会在控制台中返回“未定义”。有谁知道如何解决这个问题吗?

最佳答案

当您调用 app.init() 时,它会触发 init 并发送 api 调用来获取数据。

获取数据的调用是异步的,这意味着它不会等待响应继续执行。因此它继续执行下一行代码,即您的 console.logs。此时 API 调用尚未响应数据,因此当您尝试访问 data.property 时,它会失败,因为数据尚未到达。

当您执行log(data)时,它会创建对数据的引用的日志,当稍后用值填充引用时,该日志会在日志中更新。要获取该实例的 data 值并防止稍后更新,您可以尝试 log(JSON.stringify(data))。当您这样做时,您会得到一致的结果,您的日志都不起作用,这是实际的行为。

要使日志正常工作,请查看(同步)JAX 请求的成功/加载回调,并从那里记录它。或者,如果您稍后在 cleanData 中构造了 allData,则在 cleanData 函数之后调用日志。

因此,为了回答您的问题,您的任何日志都不应工作,因为它是异步调用。由于 console.log 处理稍后更新的引用的方式,您将记录 allData,请使用 console.log(JSON.stringify(allData)) 获取对象的实际快照

关于javascript - 对象属性未定义,但对象本身显示了所有数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42386509/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com