需求:判斷一個數組中是否有該對象,如果有則提示已存在,沒有則添加
原理:includes()方法可以判斷一個數組中是否有該項,但是對於引用類型數據,需要進行深復制,否則判斷得到的值永遠都是false
基礎代碼:
let arr = [1, 2, 3] console.log(arr.includes(1)) // true console.log(arr.includes(0)) // false let arr1=[ {name:'xiaoming',age:20}, {name:'sunyizhen',age:18} ] console.log(arr1.includes({name:'xiaoming',age:20})) // false console.log(JSON.stringify(arr1).includes(JSON.stringify({name:'xiaoming',age:20}))) // true console.log(JSON.stringify(arr1).includes(JSON.stringify({age:20,name:'xiaoming'}))) // false
應用場景:
導出字段添加至轉換字段,同一個字段不能添加兩次:
if (JSON.stringify(this.conversionList).includes(JSON.stringify(item))) return this.$message.warning('不可重復添加') this.conversionList.push(item)
同一個對象只能添加一次到table中:
if (JSON.stringify(this.tableData).includes(JSON.stringify(newObj))) return this.$message.error('單位轉換列表中已存在該項') this.tableData.push(newObj)
注意:
這種方式要求對象鍵值對按原有順序排列,順序不對結果也是返回false,以上表達的意思是includes()判斷數組是否具有某一項時要注意引用類型數據的特殊處理。