Javascript 数组上未定义映射

Javascript 数组上未定义映射,javascript,Javascript,所以我尝试迭代并映射这个数组,并从中提取数据。当试图运行代码时,我得到一个错误,说“data.data.children.map(…)。then不是函数”,即使data.data.children是数组。谢谢 var输出 取('https://www.reddit.com/r/somesubreddit/hot/.json?count=20') .then(response=>response.json()) 。然后(数据=>{ //console.log(data.data.children)

所以我尝试迭代并映射这个数组,并从中提取数据。当试图运行代码时,我得到一个错误,说“data.data.children.map(…)。then不是函数”,即使data.data.children是数组。谢谢
var输出
取('https://www.reddit.com/r/somesubreddit/hot/.json?count=20')
.then(response=>response.json())
。然后(数据=>{
//console.log(data.data.children)
data.data.children.map(命中=>output={
得分:hit.score,
标题:hit.title,
permalink:hit.permalink
})。然后(结果=>{
var done=result.sort(函数(a,b){
返回b.score-a.score
})
这是我的国家({
点击:完成
})
})

}).catch(err=>console.log(err.message));//为了说明错误
Array.prototype.map
不会返回一个
承诺
。您不能使用
.then()
链接其输出

.map()
应该是同步的,因此不需要使用
.then()
。立即使用其输出,如下所示:

var output
fetch('https://www.reddit.com/r/somesubreddit/hot/.json?count=20')
    .then(response => response.json())
    .then(data => {
        console.log(data.data.children)
        var result = data.data.children.map(hit => output = {
            score: hit.score,
            title: hit.title,
            permalink: hit.permalink
        });

        var done = result.sort(function(a, b) {
            return b.score - a.score
        })
        this.setState({
            hits: done
        })
    });
通过链接
map
sort
的输出以删除中间变量,可以进一步简化此过程:

var output
fetch('https://www.reddit.com/r/somesubreddit/hot/.json?count=20')
    .then(response => response.json())
    .then(data => {
        console.log(data.data.children)
        var result = data.data.children.map(hit => {
            score: hit.score,
            title: hit.title,
            permalink: hit.permalink
        }).sort(function(a, b) {
            return b.score - a.score
        });

        this.setState({
            hits: result
        })
    });

请记住,您只在
fetch()
调用上使用
.then()
调用,因为调用是基于承诺的。默认情况下,fetch外部或其回调中的任何实现都不会隐式使用承诺,因此您不能对它们使用
.then()

您有几个错误

  • map返回一个数组,该数组没有
    。然后
    方法
  • 这个
    output={
    …不需要
    output
    变量
  • 数据的格式与您认为的不同
  • fetch('https://www.reddit.com/r/somesubreddit/hot/.json?count=20')
    .then(response=>response.json())
    .then(data=>data.data.children.map({data:{score,title,permalink}})=>({score,title,permalink})))
    。然后(结果=>{
    var done=result.sort(函数(a,b){
    返回b.score-a.score
    });
    /*
    这是我的国家({
    点击:完成
    });
    */
    console.log(完成);
    
    })
    您有一个语法错误。您忘记了第1行的
    =
    符号正确,
    .map
    返回一个数组-数组没有
    。然后
    方法函数
    映射
    来自
    数组。原型
    返回一个数组。注意:您的问题标题有误导性…因为它是
    。然后
    没有定义