我在chatgpt它说不支持,而我百度一下,却有人说可以
在实践过后,我显示的是undefined
不支持,然而你可以自己实现一个:
class MyArray extends Array {
constructor() {
super(...arguments)
return new Proxy(this, { get(arr, index) {
index = Number(index)
if (isNaN(index)) {
throw new Error('Illegal index')
}
if (index < 0) {
index += arr.length
}
if (index < 0 || index >= arr.length) {
throw new Error('Index out of range!')
}
return arr[index]
}})
}
}
try {
const arr = new MyArray(1,2,3,4,5,6,7,8,9,10)
console.log(arr[-1])
console.log(arr[-3])
console.log(arr[7])
console.log(arr[-17])
console.log(arr[17])
} catch(e) {
console.log(e)
}
【以下回答由 GPT 生成】
JavaScript 数组不支持取负数索引值。数组的索引值从0开始,递增1。可以使用数组长度减去索引值的方式来获取数组中的元素,如果索引值是负数,则需要先将其转为正数后再进行计算。以下是一个示例代码:
let arr = [1, 2, 3, 4, 5];
let index = -2;
if (index < 0) {
index = arr.length + index;
}
console.log(arr[index]); // 输出 4
在上面的代码中,我们定义了一个数组 arr
和一个负数索引值 index
。为了获取正确的元素,我们将负数索引值转换成了正数索引值,即 arr.length + index
。通过这种方式,我们就能够成功获取到数组中对应索引位置的元素。