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);

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);
添加回答
舉報