js关于数组的常用方法(19种)
warning:
这篇文章距离上次修改已过429天,其中的内容可能已经有所变动。
push()- 在数组末尾添加一个或多个元素,并返回新的长度。
let numbers = [1, 2, 3];
numbers.push(4, 5);
console.log(numbers); // 输出: [1, 2, 3, 4, 5]pop()- 删除数组最后一个元素,并返回那个元素。
let numbers = [1, 2, 3];
let last = numbers.pop();
console.log(last); // 输出: 3
console.log(numbers); // 输出: [1, 2]shift()- 删除数组的第一个元素,并返回那个元素。
let numbers = [1, 2, 3];
let first = numbers.shift();
console.log(first); // 输出: 1
console.log(numbers); // 输出: [2, 3]unshift()- 在数组的开始添加一个或多个元素,并返回新的长度。
let numbers = [2, 3];
let count = numbers.unshift(1);
console.log(count); // 输出: 3
console.log(numbers); // 输出: [1, 2, 3]slice(start, end)- 返回从 start 到 end (不包括)之间的元素的新数组。
let numbers = [1, 2, 3, 4, 5];
let sliced = numbers.slice(2, 4);
console.log(sliced); // 输出: [3, 4]splice(start, deleteCount, ...items)- 从 start 位置开始删除 deleteCount 个元素,并且可以添加新的元素。
let numbers = [1, 2, 3, 4, 5];
numbers.splice(2, 3, 'a', 'b');
console.log(numbers); // 输出: [1, 2, 'a', 'b']concat(array1, array2, ..., arrayN)- 返回一个新数组,是将所有数组参数添加到原数组的拷贝中得到的。
let array1 = [1, 2, 3];
let array2 = [4, 5];
let concatenated = array1.concat(array2);
console.log(concatenated); // 输出: [1, 2, 3, 4, 5]join(separator)- 将数组的元素连接成一个字符串,并且可以指定一个字符串作为分隔符。
let colors = ['red', 'green', 'blue'];
let joined = colors.join(', ');
console.log(joined); // 输出: "red, green, blue"reverse()- 颠倒数组中元素的顺序。
let numbers = [1, 2, 3];
numbers.reverse();
console.log(numbers); // 输出: [3, 2, 1]sort(compareFunction)- 对数组的元素进行排序。
let numbers = [3, 1, 2];
numbers.sort((a, b) => a - b);
console.log(numbers); // 输出: [1, 2, 3]forEach(callback)- 为数组中的每个元素执行一次 callback 函数。
let numbers = [1, 2, 3];
numbers.forEach(num => console.log(num));
// 输出: 1, 2, 3map(callback)- 返回一个新数组,其中包含经过 callback 函数处理的原数
评论已关闭