【发布时间】:2019-02-08 17:45:11
【问题描述】:
我正在尝试通过将来自 Politifact API 的信息存储在一个名为“supperArray”的数组中来使用它。我通过调用 API 3 次,并将每个响应中的 10 个值推送到 superArray 来实现,如下所示:
const URL1 = "https://www.politifact.com/api/statements/truth-o-meter/people/barack-obama/json/?n=50";
const URL2 = "https://www.politifact.com/api/statements/truth-o-meter/people/hillary-clinton/json/?n=210";
const URL3 = "https://www.politifact.com/api/statements/truth-o-meter/people/bernie-s/json/?n=70";
var superArray = [];
fetch("https://cors-anywhere.herokuapp.com/"+URL1)
.then(results => {
return results.json();
})
.then(data => {
data=data.filter(function(item){return item.speaker.name_slug=="barack-obama" && item.statement_type.statement_type !== "Flip";});
for(var i=0; i<10; i++){
superArray.push(data.splice(Math.random()*data.length, 1)[0]);
}
})
fetch("https://cors-anywhere.herokuapp.com/"+URL2)
.then(results => {
return results.json();
})
.then(data => {
data=data.filter(function(item){return item.speaker.name_slug=="hillary-clinton" && item.statement_type.statement_type !== "Flip";});
for(var i=0; i<10; i++){
superArray.push(data.splice(Math.random()*data.length, 1)[0]);
}
})
fetch("https://cors-anywhere.herokuapp.com/"+URL3)
.then(results => {
return results.json();
})
.then(data => {
data=data.filter(function(item){return item.speaker.name_slug=="bernie-s" && item.statement_type.statement_type !== "Flip";});
for(var i=0; i<10; i++){
superArray.push(data.splice(Math.random()*data.length, 1)[0]);
}
})
当我要求 React 完整地记录 supperArray 时,如下所示:
console.log(superArray);
它记录了这个: 这是我所期望的。但是当我要求它记录一个特定的值时,像这样:
console.log(superArray[0]);
它记录的是undefined这是为什么?
【问题讨论】:
-
你在哪里打印你的数组?
-
我认为控制台是在愚弄你,它会在你调用 console.log 的时间点之后显示
superArray是什么。控制台不能用superArray[0]欺骗你。
标签: javascript arrays reactjs api react-native