应该JavaScript数组索引的负贡献数组长度? [英] Should negative indexes in JavaScript arrays contribute to array length?

查看:114
本文介绍了应该JavaScript数组索引的负贡献数组长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的javascript定义一个这样的数组

  VAR ARR = [1,2,3];

我也可以做

 改编[-1] = 4;

现在,如果我做

 改编=不确定;

我也输在的参考值ARR [-1]

所以对我来说逻辑上好像ARR [-1]也是一部分的改编

但是当我做以下(无设置ARR未定义)

  arr.length;

它返回的 3 不是 4

所以,我的观点是如果该阵列可负索引,使用这些负面指标也应该是其长度的一部分**。
我不知道可能是我错了,或我可能会丢失有关数组的一些概念。


解决方案

  

所以对我来说逻辑上好像ARR [-1]也是ARR的一部分。


是的,但不是在路上你认为它是。

您可以分配到一个数组(就像在JavaScript中任何其他对象),任意属性这是你在做什么,当你指数数组在 1 并分配一个值。由于这是不是数组的成员,只是一个任意的属性,你不应该指望长度来考虑该属性。

在换句话说,下面code做同样的事情:

  VAR ARR = [1,2,3];arr.cookies = 4;警报(arr.length);

In javascript I define an array like this

var arr = [1,2,3];

also I can do

arr[-1] = 4;

Now if I do

arr = undefined;

I also lose the reference to the value at arr[-1].

SO for me logically it seems like arr[-1] is also a part of arr.

But when I do following (without setting arr to undefined)

arr.length;

It returns 3 not 4;

So my point is if the arrays can be used with negative indexes, these negative indexes should also be a part of their length**. I don't know may be I am wrong or I may be missing some concept about arrays.

解决方案

SO for me logically it seems like arr[-1] is also a part of arr.

Yes it is, but not in the way you think it is.

You can assign arbitrary properties to an array (just like any other Object in JavaScript), which is what you're doing when you "index" the array at -1 and assign a value. Since this is not a member of the array and just an arbitrary property, you should not expect length to consider that property.

In other words, the following code does the same thing:

​var arr = [1, 2, 3];

​arr.cookies = 4;

alert(arr.length);

这篇关于应该JavaScript数组索引的负贡献数组长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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