at()函数

最常用的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() 方法提供了一种更直观的方式来访问数组和字符串的元素,特别是当你需要从末尾开始计数时。与传统的方括号表示法相比,它可以更方便地处理负索引。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

每天吃饭的羊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值