at 方法概述
- at 方法是 ES2022(ES13)引入的一个数组方法,它提供了一种更简洁、更直观的方式来访问数组元素
array.at(【index】)
参数 |
说明 |
index |
要访问的元素的索引位置(从零开始) |
参数值 |
说明 |
正数 |
从数组开头计算,0 表示第一个元素 |
负数 |
从数组末尾计算,-1 表示最后一个元素 |
- 返回值:返回指定索引处的元素,如果索引超出数组范围,则返回
undefined
at 方法基本用法
- 基本用法
const fruits = ["apple", "banana", "orange", "grape"];
console.log(fruits.at(1));
console.log(fruits.at(-1));
# 输出结果
banana
grape
- 与方括号表示法的比较
const arr = [10, 20, 30, 40];
console.log(arr[0]);
console.log(arr.at(0));
console.log(arr[arr.length - 1]);
console.log(arr.at(-1));
# 输出结果
10
10
40
40
at 方法注意事项
- at 方法使用负数索引时,从数组末尾计算,方括号表示法使用负数索引时,返回
undefined
const arr = [11, 22, 33, 44];
console.log(arr[-1]);
console.log(arr.at(-1));
# 输出结果
undefined
44
- at 方法超出数组范围时,返回
undefined
,方括号表示法超出数组范围时,返回 undefined
const arr = [11, 22, 33, 44];
console.log(arr[100]);
console.log(arr.at(100));
# 输出结果
undefined
undefined
concat 方法概述
- concat 方法用于合并两个或多个数组,返回一个新数组,不修改原数组
const newArray = oldArray.concat(【value】)
concat 方法特性
- 不修改原数组
const arr1 = [1, 2];
const arr2 = arr1.concat([3, 4]);
console.log(arr1);
console.log(arr2);
# 输出结果
(2) [1, 2]
(4) [1, 2, 3, 4]
- 浅拷贝机制
const arr1 = [{ a: 1 }];
const arr2 = arr1.concat();
arr1[0].a = 2;
console.log(arr2[0].a);
# 输出结果
2
- 展开一层数组参数
const arr = [1].concat([2, [3, 4]]);
console.log(arr);
# 输出结果
[1, 2, [3, 4]]
concat 方法基本用法
- 基本数组合并
const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = arr1.concat(arr2);
console.log(combined);
# 输出结果
(4) [1, 2, 3, 4]
- 合并多个数组
const arr1 = [1];
const arr2 = [2, 3];
const arr3 = [4, 5];
const merged = arr1.concat(arr2, arr3);
console.log(merged);
# 输出结果
(5) [1, 2, 3, 4, 5]
- 合并非数组值
const arr = [1].concat(2, "hello");
console.log(arr);
# 输出结果
(3) [1, 2, 'hello']
concat 方法对比展开运算符
- 展开运算符也能实现类似 concat 方法的功能
const arr1 = [1, 2];
const arr2 = [3, 4];
const merged = [...arr1, ...arr2];
console.log(merged);
# 输出结果
(4) [1, 2, 3, 4]
- concat 方法会自动展开一层数组参数,而展开运算符完全按照传入形式
const arr1 = [1].concat([2, [3]]);
const arr2 = [...[1], ...[2, [3]]];
console.log(arr1);
console.log(arr2);
# 输出结果
[1, 2, [3]]
[1, 2, [3]]
- concat 方法和展开运算符都可以接受非数组参数直接合并
const arr1 = [1].concat(2);
const arr2 = [...[1], 2];
console.log(arr1);
console.log(arr2);
# 输出结果
[1, 2]
[1, 2]