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);
添加回答
举报