【javascript】javascript数组函数 总结

目录

push()

pop()

shift()

unshift()

concat()

join()

slice()

扫描二维码关注公众号,回复: 15668049 查看本文章

splice()

sort()

reverse()


push()

作用:将一个或多个元素添加到数组的末尾,并返回新数组的长度。

const arr = [1, 2, 3];
const newLength = arr.push(4, 5);
console.log(arr);
console.log(newLength); 
// [1, 2, 3, 4, 5]
//  5

pop()

作用:从数组的末尾移除最后一个元素,并返回被移除的元素。

const arr = [1, 2, 3];
const removedElement = arr.pop();
console.log(arr);
console.log(removedElement);
// [1, 2]
//3

shift()

作用:从数组的开头移除第一个元素,并返回被移除的元素。

const arr = [1, 2, 3];
const removedElement = arr.shift();
console.log(arr);
console.log(removedElement);
// [2, 3]
// 1


unshift()

作用:从数组的开头移除第一个元素,并返回被移除的元素。

const arr = [1, 2, 3];
const newLength = arr.unshift(0, -1);
console.log(arr);
console.log(newLength);
// [0, -1, 1, 2, 3]
// 5


concat()

作用:将一个或多个元素添加到数组的开头,并返回新数组的长度。

const arr = [1, 2, 3];
const newLength = arr.unshift(0, -1);
console.log(arr);
console.log(newLength);
// [1, 2, 3, 4]


join()

作用:将数组中的所有元素连接成一个字符串。

const arr = ["Hello", "World"];
const joinedStr = arr.join(" ");
console.log(joinedStr);
// Hello World


slice()

作用:根据下标从数组中提取指定位置的元素并组成一个新数组。

const arr = [1, 2, 3, 4, 5];
const slicedArr = arr.slice(2, 4);
console.log(slicedArr);
// [3, 4]


splice()

作用:向/从数组中添加/删除元素,并返回被删除的元素。

const arr = [1, 2, 3, 4, 5];
const removedElements = arr.splice(1, 2, 6, 7);
console.log(arr);
console.log(removedElements);
// [1, 6, 7, 4, 5]
// [2, 3]


sort()

作用:对数组元素进行排序。

const arr = [3, 1, 4, 2, 5];
arr.sort();
console.log(arr);
// [1, 2, 3, 4, 5]


reverse()

作用:颠倒数组中元素的顺序。

const arr = [1, 2, 3, 4, 5];
arr.reverse();
console.log(arr);
// [5, 4, 3, 2, 1]

猜你喜欢

转载自blog.csdn.net/m0_64494670/article/details/131464024