vue陣列操作遇到坑-關於陣列操作

firefule發表於2021-09-09

經常遇到這樣一個需求,當前列表展示的內容存在一個陣列裡,然後有時候需要對這個陣列進行篩選,不顯示已經操作過的資料,比如:對管理員身份進行登記,一個管理員可以有多個身份,對於已經選擇過的身份,在操作同一個管理員時不能再次顯示。只是一個簡單的陣列篩選,每次都讓我很頭疼。
話不多說先上程式碼:

// 需求很簡單 targetTable 裡如果有 pid 與 startTable pid 一致的移除 startTable 對應物件返回新 startTable
let startTable = [
{pid: ‘3309’, rid: ‘2176430812823’, moduleName: ‘getClass’, userName: ‘songsili’},
{pid: ‘3310’, rid: ‘2176430812824’, moduleName: ‘webIndex’, userName: ‘zhangsan’},
{pid: ‘3312’, rid: ‘2176430812825’, moduleName: ‘dymanic’, userName: ‘wangwu’},
{pid: ‘3313’, rid: ‘2176430812826’, moduleName: ‘front’, userName: ‘lisi’},
{pid: ‘3314’, rid: ‘2176430812827’, moduleName: ‘static’, userName: ‘liunneg’},
{pid: ‘3315’, rid: ‘2176430812828’, moduleName: ‘former’, userName: ‘mengcan’},
{pid: ‘3316’, rid: ‘2176430812829’, moduleName: ‘pickUp’, userName: ‘lican’}
]
let targetTable = [
{pid: ‘3313’, forEvery: ‘sdfdsgsdfsd’, count: ‘1’, dateLimit: ‘2’},
{pid: ‘33015’, forEvery: ‘iiuskewrtrt’, count: ‘2’, dateLimit: ‘15’}
]
console.log(startTable)
// 第一種寫法
targetTable.forEach(param => {
// 每次迴圈找到對應下標然後移除
let indexNum = 0
let targetNum = 0
startTable.forEach(paramS => {
if (param.pid === paramS.pid) {
targetNum = indexNum
}
indexNum++
})
startTable.splice(targetNum, 1)
})
console.log(startTable)

圖片描述
然而這份程式碼寫的很艱辛,因為我知道如果在迴圈的時候操作當前陣列,下標不發生變化的時候,陣列操作會出現遍歷不完整的情況,所以我先儲存了一份匹配到的陣列,然後再對原陣列進行操作,splice操作只需要找到下標即可,includes是匹配物件是否一致,我匹配的只是某個欄位是否一致

// 需求很簡單 targetTable 裡如果有 pid 與 startTable pid 一致的移除 startTable 對應物件返回新 startTable
let startTable = [
{pid: ‘3309’, rid: ‘2176430812823’, moduleName: ‘getClass’, userName: ‘songsili’},
{pid: ‘3310’, rid: ‘2176430812824’, moduleName: ‘webIndex’, userName: ‘zhangsan’},
{pid: ‘3312’, rid: ‘2176430812825’, moduleName: ‘dymanic’, userName: ‘wangwu’},
{pid: ‘3313’, rid: ‘2176430812826’, moduleName: ‘front’, userName: ‘lisi’},
{pid: ‘3314’, rid: ‘2176430812827’, moduleName: ‘static’, userName: ‘liunneg’},
{pid: ‘3315’, rid: ‘2176430812828’, moduleName: ‘former’, userName: ‘mengcan’},
{pid: ‘3316’, rid: ‘2176430812829’, moduleName: ‘pickUp’, userName: ‘lican’}
]
let targetTable = [
{pid: ‘3313’, forEvery: ‘sdfdsgsdfsd’, count: ‘1’, dateLimit: ‘2’},
{pid: ‘33015’, forEvery: ‘iiuskewrtrt’, count: ‘2’, dateLimit: ‘15’}
]
// 第二種寫法
console.log(startTable)
let nowList = startTable.filter(items => {
var uaExist = true
targetTable.forEach(arr => {
if (arr.pid === items.pid) uaExist = false
})
if (uaExist) return items
})
console.log(nowList)

我推薦使用這種寫法篩選並不會破壞原陣列,重新賦值即可
運算元組我是很熟悉,但是在前端操作,和後端程式碼是有一定區別的,只能說類似

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/1834/viewspace-2796973/,如需轉載,請註明出處,否則將追究法律責任。

相關文章