通过数组中对象的唯一标识,来删除对象(运用到:findIndex() 、slice() )

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>通过数组中对象的唯一标识,来删除对象</title>
</head>
<body>
    <script>
        /*
        场景说明:你现在想通过id来删除数组中的某个对象

        知识点:
        findIndex()方法返回数组中满足提供的测试函数的第一个元素的索引。否则返回-1。
        
        slice()方法提取一个字符串的一部分,并返回一新的字符串。
        详解:注意:slice() 提取的新字符串包括beginSlice但不包括 endSlice。
                例1:str.slice(1, 4) 提取新字符串从第二个字符到第四个 (字符索引值为 1, 2, 和 3)。
                例2:str.slice(2, -1) 提取第三个字符到倒数第一个字符。
        */
        const todos=[
            {id:1,name:'XYZ',completed:true},
            {id:2,name:'LM',completed:true},
            {id:3,name:'CMJ',completed:false},
            {id:4,name:'FZH',completed:false},
            {id:5,name:'LS',completed:false},

        ]
        const id=3;
        const todoIndex=todos.findIndex(todo=>todo.id===id);
        const newTodos=[...todos.slice(0,todoIndex),...todos.slice(todoIndex+1)]
        console.log(newTodos);
    </script>
</body>
</html>

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值