最常用的arr.at(-1), arr.at(0)
得到数组的最后一个值,和pop()的区别是pop()会改变原数组,at(-1)不会
得到数组的第一个值,和shift()的区别是shift()会改变原数组,at(0)不会
数组中使用 at()
方法
1. 使用正索引访问元素
const fruits = ['apple', 'banana', 'cherry', 'date'];
// 使用 at() 方法通过正索引访问元素
const firstFruit = fruits.at(0);
const secondFruit = fruits.at(1);
console.log(firstFruit); // 输出: apple
console.log(secondFruit); // 输出: banana
2. 使用负索引访问元素
const fruits = ['apple', 'banana', 'cherry', 'date'];
// 使用 at() 方法通过负索引访问元素
const lastFruit = fruits.at(-1);
const secondLastFruit = fruits.at(-2);
console.log(lastFruit); // 输出: date
console.log(secondLastFruit); // 输出: cherry
3. 处理索引越界情况
const fruits = ['apple', 'banana', 'cherry', 'date'];
// 尝试访问超出数组范围的索引
const outOfBoundsPositive = fruits.at(10);
const outOfBoundsNegative = fruits.at(-10);
console.log(outOfBoundsPositive); // 输出: undefined
console.log(outOfBoundsNegative); // 输出: undefined
字符串中使用 at()
方法
1. 使用正索引访问字符
const message = 'Hello';
// 使用 at() 方法通过正索引访问字符
const firstChar = message.at(0);
const secondChar = message.at(1);
console.log(firstChar); // 输出: H
console.log(secondChar); // 输出: e
2. 使用负索引访问字符
const message = 'Hello';
// 使用 at() 方法通过负索引访问字符
const lastChar = message.at(-1);
const secondLastChar = message.at(-2);
console.log(lastChar); // 输出: o
console.log(secondLastChar); // 输出: l
3. 处理索引越界情况
const message = 'Hello';
// 尝试访问超出字符串范围的索引
const outOfBoundsPositive = message.at(10);
const outOfBoundsNegative = message.at(-10);
console.log(outOfBoundsPositive); // 输出: undefined
console.log(outOfBoundsNegative); // 输出: undefined
at()
方法提供了一种更直观的方式来访问数组和字符串的元素,特别是当你需要从末尾开始计数时。与传统的方括号表示法相比,它可以更方便地处理负索引。