土拨鼠爱coding 2023-09-18 11:53 采纳率: 0%
浏览 3

JavaScript

JavaScript 数组 到底支不支持 取负数索引值

img

我在chatgpt它说不支持,而我百度一下,却有人说可以

在实践过后,我显示的是undefined

  • 写回答

2条回答 默认 最新

  • RivaJ 2023-09-18 12:17
    关注

    不支持,然而你可以自己实现一个:

         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)
          }
    
    评论

报告相同问题?

问题事件

  • 创建了问题 9月18日