数组里面的状态为true和false,我想把为前三个为true的,就为true,后面的还有true的变为false怎么实现呢?

最好的陪521yyf
  • 721

现在我的数组里面有name 和 status

 let data=[
       {name:"小明",status:false},
       {name:"小红",status:false},
       {name:"小张",status:true},//一次出现
       {name:"小墙",status:false},
       {name:"小粉",status:false},
       {name:"小军",status:false},
       {name:"小钰",status:false},
       {name:"小访",status:true},//二次出现
       {name:"小源",status:false},
       {name:"小方式",status:false},
       {name:"小佛",status:true},//三次出现  三次之后  还有true的变为false
       {name:"小付款",status:true},
       {name:"小哦咯",status:true},
       {name:"小来了",status:false},
   ]
        console.log(data);
        

我想把从第一个开始算,一直到出现过三个true,然后把剩下的都变为false,这个怎么实现呢?

回复
阅读 1.7k
5 个回答
✓ 已被采纳
let count = 0;
for(let item of data){
    if(count < 3){
        item.status && ++count
    }else{
        item.status = false;
    }
}
        let data = [
            { name: "小明", status: false },
            { name: "小红", status: false },
            { name: "小张", status: true },//一次出现
            { name: "小墙", status: false },
            { name: "小粉", status: false },
            { name: "小军", status: false },
            { name: "小钰", status: false },
            { name: "小访", status: true },//二次出现
            { name: "小源", status: false },
            { name: "小方式", status: false },
            { name: "小佛", status: true },//三次出现  三次之后  还有true的变为false
            { name: "小付款", status: true },
            { name: "小哦咯", status: true },
            { name: "小来了", status: false },
        ];
        let count = 0;
        data.forEach(obj => {
            if (count >= 3) {
                obj.status = false;
                return;
            }
            if (obj.status) {
                count++;
            }
        })
        console.log(data);
let total = 0;
let result = data.map(k => {     
   if(k.status) {total++};
   if(total>3 && k.status) {k.status=false}
   return k;
});
data.reduce((count, cur) => {
  return count < 3 && cur.status ? ++count : (cur.status = false, count)
}, 0)
console.log(data)

竟然有这种问题

你知道吗?

宣传栏