方法一:用delete 删除数组中元素,在谷歌浏览器控制台测试如下:
代码如:
//输出数组中的元素 var getArray = function(array){ //循环数组元素 for(var i=0;i<array.length; i++) { console.log("第"+ (i+1) +"个元素:"+ array[i]); } }
//定义数组 var array=["aa","dd","cc","aa"]; //方法1:delete删除数组元素 delete array[1]; //输出结果 : ["aa",undefined,"cc","aa"] getArray(array);
方法二:用splice删除数组的元素,使用谷歌浏览器控制台测试如下:
//输出数组中的元素 var getArray = function(array){ //循环数组元素 for(var i=0;i<array.length; i++) { console.log("第"+ (i+1) +"个元素:"+ array[i]); } } //定义数组 var array = ["aa","dd","cc","aa"]; //方法2:删除数组元素 array.splice(1,1); //输出结果:["aa","cc","aa"] getArray(array);
实际功能有:
实现代码:
// 右侧已选列表删除元素,左侧复选框的选中状态也要更改 delRole (index) { let _this = this let delRole = _this.roleSelectedList[index].role_code _this.$set(_this.roleSelectedList[index], '_checked', false) _this.rolesList.forEach(item => { if (item.role_code === delRole) { _this.$set(item, '_checked', false) // 点击×号时不仅取消左边的勾选,同时也去掉右边要叉掉的元素 _this.roleSelectedList.splice(index, 1) } }) }, <div class="content-right flex-item"> <div class="header-input"> <span class="selected">已选</span> <h-input placeholder="请输入角色名称" v-model="orgName" icon="search" @on-click="search(orgName)" ></h-input> </div> <ul> <li v-for="(item, index) in roleSelectedList" :key="index"> <template v-if="item._checked"> <span @click="delRole(index)">x</span> {{item.role_name}} </template> </li> </ul> </div>
总结:
delete 和splice方法的区别
1)delete: 只是被删除的元素变成了 undefined 其他的元素的键值还是不变。
2) splice: 该方法会改变原始数组