利用concat
function pre(arr, item) {
return [item].concat(arr);
}
使用push.apply
function pre(arr, item) {
var newArr = [item];
[].push.apply(newArr, arr);
return newArr;
}
利用slice+unshift/splice
function pre(arr, item) {
var newArr = arr.slice(0);
newArr.unshift(item);
return newArr;
}
function pre(arr, item) {
var newArr = arr.slice(0);
newArr.splice(0,0,item);
return newArr;
}
使用join+split+unshift/splice组合
注意:数组元素将转为字符串类型
function pre(arr, item) {
var newArr = arr.join().split(',');
newArr.unshift(item);
return newArr;
}
function pre(arr, item) {
var newArr = arr.join().split(',');
newArr.splice(0,0,item);
return newArr;
}
普通的迭代拷贝
function pre(arr, item) {
var newArr = [];
for (var i = 0; i < arr.length; i++) {
newArr.push(arr[i]);
}
newArr.unshift(item);
return newArr;
}
使用push
function pre(arr, item) {
var newArr = [];
newArr.push(item);
for (var i = 0; i < arr.length; i++) {
newArr.push(arr[i]);
}
return newArr;
}
es6 …
function pre(arr, item) {
let newArray = [...arr];
newArray.unshift(item);
return newArray;
}