<ol><li>at() 方法可用于获取数组或字符串中指定索引的元素,支持负索引从末尾开始计数,如 array.at(-1) 获取最后一个元素;2. 当索引超出范围时返回 undefined,不会报错,比传统方括号方式更安全;3. 代码可读性和简洁性优于 array[array.length - 1] 的写法;4. 主要劣势是浏览器兼容性较差,旧版浏览器需使用 polyfill 或传统方式;5. at() 方法也适用于字符串,但不直接支持如 arguments 等类数组对象,需先转换为数组才能使用;6. 现代浏览器已广泛支持,但在需要兼容旧环境时应谨慎使用或提供降级方案。</li></ol>

使用
at()
[]
解决方案:
at()
array.at(0)
array.at(-1)
const myArray = ['apple', 'banana', 'cherry']; // 获取第一个元素 const firstElement = myArray.at(0); // 'apple' // 获取最后一个元素 const lastElement = myArray.at(-1); // 'cherry' // 获取倒数第二个元素 const secondLastElement = myArray.at(-2); // 'banana'
如果索引超出数组的范围,
at()
undefined
const myArray = ['apple', 'banana', 'cherry']; // 索引超出范围 const outOfBoundsElement = myArray.at(5); // undefined const outOfBoundsElementNegative = myArray.at(-5); // undefined
使用
at()
array[array.length - 1]
array.at(-1)
at()
at()
at()
if (!Array.prototype.at) {
Array.prototype.at = function(n) {
// 将索引转换为整数
n = Math.trunc(n) || 0;
// 如果索引为负数,则从数组末尾开始计算
if (n < 0) {
n += this.length;
}
// 如果索引超出范围,则返回 undefined
if (n < 0 || n >= this.length) {
return undefined;
}
// 返回指定索引的元素
return this[n];
};
}这段代码首先检查
Array.prototype.at
at
n
Math.trunc(n) || 0
undefined
at()
优势:
at()
array.at(-1)
array[array.length - 1]
at()
undefined
劣势:
at()
at()
总的来说,
at()
除了数组,
at()
at()
const myString = "hello"; // 获取第一个字符 const firstChar = myString.at(0); // "h" // 获取最后一个字符 const lastChar = myString.at(-1); // "o"
需要注意的是,
at()
arguments
at()
arguments
at()
function myFunction() {
// 将 arguments 对象转换为数组
const argsArray = Array.from(arguments);
// 使用 at() 方法访问数组元素
const firstArg = argsArray.at(0);
console.log(firstArg);
}
myFunction(1, 2, 3); // 输出 1总结来说,
at()
以上就是js 如何用at获取数组指定索引的元素的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号