### 判斷兩組數組對象中是否有重復值
* 第一種:
let list = [[1,2,3],[1,5,4]];
let obj = {};
let msg = ''
list.forEach((e, index) => {
for (var key in e) {
if (!obj[e[key].val]) {
obj[e[key].val] = true;
} else {
return msg = `第${~~index + 1}個第${~~key+1}行重復了`
}
}
})
return msg
* 第二種
let list = this.data.msgList.reduce((acc, val) => acc.concat(val), []);
if([...new Set(specList.map(item=>item.specDesc))].length < specList.length){
console.log('有重復')
}
### 數組合並
obj.push.apply(obj,[])
### 小程序 或者 vue 中改變對象值引用
JSON.parse(JSON.stringify(obj))
let arr1 = [1, 2, 4, 4, 3, 3, 1, 5, 3];
求:arr1 數組中重復的值
思路:定一個空數組用來放相同的值,該數組循環兩次,對比!
//關鍵代碼 for(var j of arr){ for(var i of arr){ if(j === i && newArr.indexOf(j) == -1){ newArr.push(j) } } } return newArr
悲劇的是,返回值是沒有重復值跟我想的不一樣 返回:[1,2,3,4,5]
修改一下
j !== i
返回 [1,2]
然后看了別人的代碼
let arr = [1, 2, 4, 4, 3, 3, 1, 5, 3]; function duplicates(arr) { var result = []; arr.forEach(item => {
//判斷檢查數據從頭到尾 與 從尾到頭 的位置是否 不同 並且 每次判斷 新數組里面是否有 當前值的 位置 沒有那么 進行下一步 if (arr.indexOf(item) !== arr.lastIndexOf(item) && result.indexOf(item) == -1) { result.push(item); } }) return result //返回 1 3 4 } duplicates(arr)
唯一的缺點就是復雜度上升
arr.indexOf(item) 返回 0 1 2 2 4 4 0 7 4 arr.lastIndexOf(item) 返回 6 1 3 3 8 8 6 7 8 arr.indexOf(item) !== arr.lastIndexOf(item) 返回 true false true true true true true false true
為true的時候
出現了 1 4 4 3 3 1 3
然后
result.indexOf(item) == -1) 每次都要跟當前值 做對比 如果有 ,那么就不push 進去
那么 1 4 不push 3 不push 不push
最終返回143,第一次做感覺非常難,但是仔細想了之后,明白之后也就這樣~~-,-