微信小程序中需要用到數組的操作,push和concat二者功能很相像,但有兩點區別。
先看如下例子:
var arr = []; arr.push(1); arr.push(2); arr.push([3, 4]) arr.push(5, 6); arr = arr.concat(7); arr = arr.concat([8, 9]); arr = arr.concat(10, 11); for(var i in arr){ console.log(i+"-----"+arr[i]); }
打印結果如下:
index.js [sm]:180 0-----1
index.js [sm]:180 1-----2
index.js [sm]:180 2-----3,4
index.js [sm]:180 3-----5
index.js [sm]:180 4-----6
index.js [sm]:180 5-----7
index.js [sm]:180 6-----8
index.js [sm]:180 7-----9
index.js [sm]:180 8-----10
index.js [sm]:180 9-----11
區別:
push 遇到數組參數時,把整個數組參數作為一個元素;而 concat 則是拆開數組參數,一個元素一個元素地加進去。
push 直接改變當前數組;concat 不改變當前數組。
注意:arr1=arr1.concat(arr2)