js删除数组中一条数据的方法

2022-08-03 08:29:25

首先介绍下数组操作中 filter 和 splice 方法的区别:

filter:
 array.filter(function(currentValue,index,arr), thisValue)

currentValue,index,arr 当前元素的值或者索引(可选)或数组(可选),thisValue 用于改变this指向 默认指向window 。
filter 是过滤的意思,所以这个方法的作用就是返回一个匹配过滤条件的新数组

示例:

var ages=[32,33,16,40];
	
document.getElementById("demo").innerHTML= ages.filter(function(age){return age>=18;});//	32	33	40
splice:
array.splice(index,howmany,item1,.....,itemX)

index规定从何处添加/删除元素,howmany规定应该删除多少元素。必须是数字,可以是0。最后的item(可选) 是要添加的元素。
splice 方法用于添加或删除数组中的元素。
示例:

var fruits=["Banana","Orange","Apple","Mango"];
fruits.splice(2,2);// 表示在索引2开始删除 删除两个元素var x=document.getElementById("demo").innerHTML=fruits;//	Banana,Orange

下面开始介绍一下我在 vue 项目中用到的删除数组中元素的案例

filter方法:
<template><div><iclass="el-icon-close" @click="del(todo)"></i></div></template><script>exportdefault{
  name:'todoList',data(){return{
      todolist:[]}},created(){},mounted(){},
  methods:{del(todo){// 也可以 不如splice好this.todolist=this.todolist.filter(item=>item!==todo)// 删就是取反 返回新数组}}}</script><style lang="less" scoped></style>
splice方法:
<template><div><iclass="el-icon-close" @click="del(index)"></i></div></template><script>exportdefault{
  name:'todoList',data(){return{
      todolist:[]}},created(){},mounted(){},
  methods:{del(index){this.todolist.splice(index,1)}}}</script><style lang="less" scoped></style>

两者比较可以看出splice方法 更加简洁易懂 所以更推荐splice方法

  • 作者:alokka
  • 原文链接:https://blog.csdn.net/alokka/article/details/89945990
    更新时间:2022-08-03 08:29:25