导航
arr.push(item1, item2, ..., itemX)
var arr = [1, 2, 3];
arr.push(1);
var result = arr.push(1, 2, 3);
console.log(arr, result);
arr.unshift(item1, item2, ..., itemX)
var arr = [1, 2, 3];
arr.unshift(1);
var result = arr.unshift(2, 3);
console.log(arr, result);
var arr = [1, 2, 3];
Array.prototype.selfPush = function() {
var args = arguments;
for (var i = 0; i < args.length; i++) {
this[this.length] = args[i];
}
return this.length;
}
var result = arr.selfPush(4, 5, 6);
console.log(arr, result);
arr.pop()
var arr = [1, 2, 3];
var res = arr.pop();
console.log(arr, res);
arr.shift()
var arr = [1, 2, 3];
var res = arr.shift();
console.log(arr, res);
arr.reverse()
var arr = [1, 2, 3];
let res = arr.reverse(); // [ 3, 2, 1 ]
res.splice(3, 0, 0);
console.log(arr, res); // [ 3, 2, 1, 0 ] [ 3, 2, 1, 0 ]
返回值:由被删除的元素组成的一个数组。如果只删除了一个元素,则返回只包含一个元素的数组。如果没有删除元素,则返回空数组。
var arr = ['a', 'b', 'c', 'd', 'e', 'f'];
var res = arr.splice(1, 2); // 从下标 1 这个位置开始,删除两个元素
console.log({
res,
arr
});
var arr = ['a', 'b'];
var res = arr.splice(2, 0, 'c', 'd');
// 在下标 2 这个元素开始,删除 0 个元素,再从下标 2 开始新增两个元素 'c', 'd'
console.log({
res,
arr
});
var arr = [1,2,3]
arr.splice(1,0,4)
console.log(arr) // [1,4,2,3]
var arr = ['a', 'b', 'c', 'd', 'e', 'f'];
var res = arr.splice(1, 2, 3);
console.log({
res,
arr
});
var arr = [1, 2];
console.log(
arr.splice(10, 2, 1, 2, 3),
arr
); // [] [1,2,1,2,3]
var arr = ['a', 'b', 'c', 'd', 'f'];
var res = arr.splice(-1, 0, 'e');
console.log({
res,
arr
});
[1, 2, 3, 4, 5]
找 -2 是哪个 -2 + 5 = 3function splice(arr, index) {
return index += index >= 0 ? 0 : arr.length;
}
var arr = ['a', 'b', 'c', 'd', 'f'];
var idx = splice(arr, -2);
console.log(arr[idx]);
arr.sort((a, b) => a - b)
var arr = [9, 4, 6, 0, 3, -2];
console.log(arr.sort());
var arr2 = ['r', 'v', 'g', 's', 't', 'a', 'c'];
console.log(arr2.sort());
var arr = [29, 30, 20, 25, 9, 6];
console.log(arr.sort())