亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將數組中的項目移動到javascript中的頂部

將數組中的項目移動到javascript中的頂部

慕容708150 2021-07-02 14:05:19
我需要從一個數組中刪除一個項目,然后將其放入另一個數組的頂部。我目前有一系列文章,其中一些文章的類型英雄是真實的,而其他文章則是常規的。我需要找到數組中的第一篇英雄文章并將其刪除。然后把這篇文章放到另一個數組的頂部。任何幫助將非常感激。謝謝我目前有這個:articles = [    {title: "article 1", hero: false},    {title: "article 2", hero: false},    {title: "article 3", hero: true},    {title: "article 4", hero: false},    {title: "article 5", hero: true},    {title: "article 6", hero: false},    {title: "article 7", hero: true}]但想要這個結果:articles = [    {title: "article 1", hero: false},    {title: "article 2", hero: false},    {title: "article 4", hero: false},    {title: "article 5", hero: true},    {title: "article 6", hero: false},    {title: "article 7", hero: true}]hero = [    {title: "article 3", hero: true}]
查看完整描述

3 回答

?
白衣染霜花

TA貢獻1796條經驗 獲得超10個贊

試試這個:


const articles = [

    {title: "article 1", hero: false},

    {title: "article 2", hero: false},

    {title: "article 3", hero: true},

    {title: "article 4", hero: false},

    {title: "article 5", hero: true},

    {title: "article 6", hero: false},

    {title: "article 7", hero: true},

];


const heros = [];


for(let [i, article] of articles.entries())

{

  if(article.hero)

    {

    heros.unshift(article);

    articles.splice(i, 1);

    break;

    }

}


console.log(heros);

console.log(articles);


查看完整回答
反對 回復 2021-07-08
?
慕的地8271018

TA貢獻1796條經驗 獲得超4個贊

您可以使用.findIndex()來獲取英雄等于 的第一篇文章true。然后,您可以使用此索引將對象添加到hero數組中,然后再次使用它從articles數組中刪除.splice()。


請參閱下面的示例:


const articles = [

    {title: "article 1", hero: false},

    {title: "article 2", hero: false},

    {title: "article 3", hero: true},

    {title: "article 4", hero: false},

    {title: "article 5", hero: true},

    {title: "article 6", hero: false},

    {title: "article 7", hero: true}

];

const hero = [];

const foundArticle = articles.findIndex(({hero}) => hero);

hero.push(articles[foundArticle]);

articles.splice(foundArticle, 1);


console.log(articles);

console.log(hero);

對于 IE 支持,您可以手動查找索引而不是使用.findIndex():

function findObjInArr(arr, cb) {

  for(let i = 0; i < arr.length; i++) {

    let obj = arr[i];

    if(cb(obj)) {

      return i;

    }

  }

  return -1;

}


const articles = [

    {title: "article 1", hero: false},

    {title: "article 2", hero: false},

    {title: "article 3", hero: true},

    {title: "article 4", hero: false},

    {title: "article 5", hero: true},

    {title: "article 6", hero: false},

    {title: "article 7", hero: true}

];


const hero = [];

const foundArticle = findObjInArr(articles, function(obj) {

  return obj.hero;

});

hero.push(articles[foundArticle]);

articles.splice(foundArticle, 1);


console.log(articles);

console.log(hero);


查看完整回答
反對 回復 2021-07-08
  • 3 回答
  • 0 關注
  • 181 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號