Array.prototype.at()
- 描述:
at()
方法接收一个整数值并返回该索引对应的元素,允许正数和负数。负整数从数组中的最后一个元素开始倒数。 - 语法:
array.at(y)
- 参数:要返回的数组元素的索引(从零开始),会被转换为整数
- 返回值:返回数组中与给定索引匹配的元素;负数索引从数组末尾开始计数——如果
index < 0
,则会访问index + array.length
位置的元素 - 临界值:
index < -array.length
或index >= array.length
,返回undefined
Math.floor(x)
- 语法:
Math.floor(x)
- 参数:会被隐式转换为Number类型
- 返回值:小于等于
x
的最大整数
代码实现
Array.prototype.at = function at(num) {
const self = this
const len = self.length
let intNum = Math.floor(num)
if (typeof num === "string" || intNum === 0) return self[0]
if (!intNum || (intNum > 0 && intNum > len) || (intNum < 0 && intNum < -len)) {
return
} else if (intNum < 0) {
intNum = intNum + len
}
return self[intNum]
}
// const array1 = [5, 12, 8, 130, 44];
const colors = ["red", "green", "blue"];
console.log(colors.at(-2))