使用
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 //m.sbmmt.com/ All Rights Reserved | php.cn | 湘ICP备2023035733号