【问题标题】:Cant access fetched elements of an array [duplicate]无法访问获取的数组元素[重复]
【发布时间】:2020-01-07 17:09:33
【问题描述】:

我想通过估计的人口值对获取的数据进行排序。但是当我获取数据并将名称和数字对象映射到新数组时,我什至无法访问数组中的单个对象。

已经尝试使用 lodash、Array.from() 进行映射/转换,使用扩展运算符进行复制,...

请有人解释一下为什么?谢谢。

代码:

d3 = require("d3")
_ = require("lodash")

const countries = []
const data = d3.tsv("https://cdn.jsdelivr.net/npm/world-atlas@1/world/110m.tsv")
    .then(d => d.map( c => {
        countries.push({
            name: c.name,
            pop_est: +c.pop_est
        })
        return countries
    }))

console.log(countries) // --> i get the array of objects 

let a = countries[0]
console.log(a) // undefined

console.log(countries.sort((a, b) => b.pop_est - a.pop_est)) // doesn´t sort

控制台输出:

[]
0: {name: "Kosovo", pop_est: 1804838}
1: {name: "Somaliland", pop_est: 3500000}
2: {name: "N. Cyprus", pop_est: 265100}
3: {name: "Afghanistan", pop_est: 28400000}
4: {name: "Angola", pop_est: 12799293}
5: {name: "Albania", pop_est: 3639453}
6: {name: "United Arab Emirates", pop_est: 4798491}
7: {name: "Argentina", pop_est: 40913584}
8: {name: "Armenia", pop_est: 2967004}
9: {name: "Antarctica", pop_est: 3802}
10: {name: "Fr. S. Antarctic Lands", pop_est: 140}
undefined
0: {name: "Kosovo", pop_est: 1804838}
1: {name: "Somaliland", pop_est: 3500000}
2: {name: "N. Cyprus", pop_est: 265100}
3: {name: "Afghanistan", pop_est: 28400000}
4: {name: "Angola", pop_est: 12799293}
5: {name: "Albania", pop_est: 3639453}
6: {name: "United Arab Emirates", pop_est: 4798491}
7: {name: "Argentina", pop_est: 40913584}
8: {name: "Armenia", pop_est: 2967004}
9: {name: "Antarctica", pop_est: 3802}
10: {name: "Fr. S. Antarctic Lands", pop_est: 140}

【问题讨论】:

    标签: javascript arrays sorting d3.js


    【解决方案1】:

    这看起来像是一个关于 JavaScript hoisting 和本质上是单线程的问题。

    您需要在回调中添加代码

    const data = d3.tsv("https://cdn.jsdelivr.net/npm/world-atlas@1/world/110m.tsv")
        .then(d => d.map( c => {
            countries.push({
                name: c.name,
                pop_est: +c.pop_est
            })
         console.log(countries) // --> i get the array of objects 
    
          let a = countries[0]
          console.log(a) // undefined
    
          console.log(countries.sort((a, b) => b.pop_est - a.pop_est)) // doesn´t sort
        }))
    
    
    

    .then in javascript 是一个你会想要阅读的承诺

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多