方法一:用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: 該方法會改變原始數組
