首页 > 解决方案 > javascrpit 中的 Array.push 用最后一个推送的值替换所有预先存在的值,保持长度不变

问题描述

我正在抓取网站的数据,并在将对象推送到 javascript 列表时生成最终结果,它将所有预先存在的值替换为最后推送的值。

当我在推送之前 console.logged 它时,我得到了正确的答案。

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' } ] }

他们都应该是不同的

标签: node.jspushcheerio

解决方案


推荐阅读