Why can't I do array[-1] in JavaScript?

前端 未结 4 1434
春和景丽
春和景丽 2021-01-15 00:36

In Python, you can do that:

arr = [1,2,3]
arr[-1] // evaluates to 3

But in JS, you can\'t:

let arr = [1,2,3];
arr[-1]; // e         


        
相关标签:
4条回答
  • 2021-01-15 00:56

    You can use arr[-1] - it will try to access the -1 property on the arr object, which is possible when weird code has assigned to the negative index. For example:

    const arr = [1,2,3]
    arr[-1] = 'foo';
    console.log(arr[-1]);

    Javascript property access has always worked this way - so, changing things so that [-1] will refer to the last item in the array would be a breaking change, which the standards strive very hard to avoid. (remember how they backed out of the Array.prototype.flatten name due to incompatibility with an extremely old and obsolete version of MooTools which still exists on only a few sites - this would be far worse)

    0 讨论(0)
  • 2021-01-15 00:56

    Use .slice(-N)[0]:

    const array = [1, 2, 3]
    
    console.log(array.slice(-1)[0])  // 3
    console.log(array.slice(-2)[0])  // 2
    console.log(array.slice(-3)[0])  // 1

    In Strings you have another option (instead of [0]).

    const string = 'ABC'
    
    console.log(string.slice(-1))      // 'C'
    console.log(string.slice(-2, -1))  // 'B'
    console.log(string.slice(-3, -2))  // 'A'

    Or using .substr(-N, 1):

    const string = 'ABC'
    
    console.log(string.substr(-1))     // 'C'
    console.log(string.substr(-2, 1))  // 'B'
    console.log(string.substr(-3, 1))  // 'A'

    0 讨论(0)
  • 2021-01-15 01:05

    You miss the point, that arrays are objects (exotic object) and -1 is a valid key.

    var array = [1, 2, 3];
    
    array[-1] = 42;
    
    console.log(array);
    console.log(array[-1]);

    0 讨论(0)
  • 2021-01-15 01:20

    Because most languages like the indexOf function to return -1 instead of a needless exception. If -1 is a valid index then following code would result in 3 instead of undefined.

    var arr = [1,2,3]
    console.log(arr[arr.indexOf(4)])

    IMHO, Python made a mistake by make negative indexes valid, because it leads to many strange consequences that are not directly intuitive.

    0 讨论(0)
提交回复
热议问题