javascrpit中的Array.push将所有先前存在的值替换为最后推送的值,并保持长度相同

时间:2019-01-08 10:36:13

标签: node.js push cheerio

我正在抓取一个网站来获取数据,并在将对象推送到javascript列表中时得出最终结果,它将所有先前存在的值替换为最后推送的值。

当我在按下它之前进行控制台登录时,我得到了正确的答案。

function getCharactersfor(name,filter='anime'){
return rp("https://www.anime-planet.com/"+filter+"/"+change(name)+"/characters").then((data) => { 
    const $=cheerio.load(data)
    result=[]
    a=$("tr").each(function(){
        character={name:undefined,image:undefined,voiceActors:{English:[],Japanese:[]}}
        character.name=$(this).find(".name").text()
        character.image="https://www.anime-planet.com"+$(this).find('.tableAvatar').find('img').attr('src')
        if(filter=='anime'){
            res={name:'',image:undefined,otherworks:[]}
            m=$(this).find(".flagUS").children().each(function(i){
               res.name=$(this).html()
               a=cheerio.load($(this).attr('title'))
               res.image="https://www.anime-planet.com"+a('img').attr('src')
               character.voiceActors.English.push(res)
            })
            m=$(this).find(".flagJP").children().each(function(){
                res.name=$(this).html()
                a=cheerio.load($(this).attr('title'))
                res.image="https://www.anime-planet.com"+a('img').attr('src')
                character.voiceActors.Japanese.push(res)
            })
        }else{
            character.voiceActors=undefined
        }
        result.push(character)
    })
    return(result)
}).catch(err=> console.log(err))
}
getCharactersfor('black clover').then((result)=>{
     console.log(result[0].voiceActors)
})

结果显示为

{ English:

   [ { name: 'Gakuto KAJIWARA',
       image: 'https://www.anime-planet.com/images/people/thumbs/gakuto-kajiwara-23630.jpg?t=1509881610' } ],

  Japanese:
   [ { name: 'Gakuto KAJIWARA',
       image: 'https://www.anime-planet.com/images/people/thumbs/gakuto-kajiwara-23630.jpg?t=1509881610' },

{ name: 'Gakuto KAJIWARA',
       image: 'https://www.anime-planet.com/images/people/thumbs/gakuto-kajiwara-23630.jpg?t=1509881610' } ] }

所有这些都应该不同

0 个答案:

没有答案