JavaScript 數組合並去重實現
阿新 • • 發佈:2021-12-12
一、數組合並
方法一、for迴圈實現數組合並
程式碼如下:
let arr1 = ['a','b','c'] let arr2 = [1,2,3] for (let i in arr2) { arr1.push(arr2[i]) } console.log("arr1:",arr1) console.log("arr2:",arr2)
結果如下:
方法二、arr1.push.apply(arr1,arr2)實現數組合並(比方法一好)
程式碼如下:
let arr1 = ['a','b','c'] let arr2 = [1,2,3] arr1.push.apply(arr1,arr2) console.log("arr1:",arr1) console.log("arr2:",arr2)
結果如下:
方法三、concat方法合併倆陣列生成新的陣列
程式碼如下:
let arr1 = ['a','b','c'] let arr2 = [1,2,3] arr1 = arr1.concat(arr2) console.log("concat方法") console.log("arr1:",arr1) console.log("arr2:",arr2)
結果如下:
方法四、ES6語法
程式碼如下:
let arr1 = ['a','b','c'] let arr2 = [1,2,3] arr1 = [...arr1, ...arr2] console.log("ES6語法") console.log("arr1:",arr1) console.log("arr2:",arr2)
結果如下:
方法5、ES6語法+push方法
程式碼如下:
let arr1 = ['a','b','c'] let arr2 = [1,2,3] arr1.push(...arr2) console.log("ES6語法+push方法") console.log("arr1:",arr1) console.log("arr2:",arr2)
結果如下:
二、陣列去重
set方法去重
程式碼如下:
var arr = [1, 1, 2, 2, 2, 3, 3, 3] let res = Array.from(new Set(arr)) console.log(res)
結果如下: