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

前端 未结 4 1445
春和景丽
春和景丽 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 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.

提交回复
热议问题