为什么我不能在 JavaScript 中做 array[-1] ? [英] Why can't I do array[-1] in JavaScript?

查看:22
本文介绍了为什么我不能在 JavaScript 中做 array[-1] ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 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).

我错过了什么?

推荐答案

你没看明白,数组是对象(exotic object)而 -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] ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆