问题描述
在Python中,您可以这样做:
In Python, you can do that:
arr = [1,2,3]
arr[-1] // evaluates to 3
但是在JS中,您不能:
But in JS, you can't:
let arr = [1,2,3];
arr[-1]; // evaluates to undefined
问题是: 为什么?
The question is: why?
我知道解决它的技巧(arr[arr.length-1]
,修改数组原型等),但这不是重点.
I know about the tricks to get around it (arr[arr.length-1]
, modifying the array prototype, etc), but that is not the point.
我试图理解为什么EcmaScript标准中仍然没有将负数组索引解释为从结尾开始的索引,尽管实现理解这一点的JS引擎(以及整个引擎)似乎很容易Python社区对此表示欢迎.
I'm trying to understand why it is still not in the EcmaScript standards to interpret negative array indices as indices starting from the end, despite that it seems pretty easy to implement a JS engine that understands that (and also, the whole Python community is having a blast with this notation).
我想念什么?
推荐答案
您忘了一点,数组是对象(异国对象),而-1
是有效键.
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]);
这篇关于为什么我不能在JavaScript中执行array [-1]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!