是否JavaScript的填充空数组项? [英] Does JavaScript populate empty array items?

查看:116
本文介绍了是否JavaScript的填充空数组项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编码了很多年的数据在JavaScript中,我正在考虑将它添加到阵列,用一年的数组索引,并把数据放入数组。然而,萤火虫似乎表明的JavaScript通过与阵列中的填充2000奇数项处理这种未定义。随着数百个这样的阵列在活动内存踢周围,我很担心,成千上万的无用的数组中元素的开销可能会开始拖慢了程序。会这样吗?

I am coding a lot of annual data in JavaScript, and I was considering adding it to arrays, using the year as the array index and putting the data into the array. However, Firebug seems to be indicating that JavaScript handles this by populating two thousand odd entries in the array with "undefined." With hundreds of such arrays kicking around in active memory, I'm worried the overhead of hundreds of thousands of useless array items could start to slow the program down. Will it?

推荐答案

当您设置一个数字指数值高于当前阵列的长度长度属性将受到影响。

When you set the value of a numeric index higher than the current length of your array, the length property is affected.

在简单地说,你应该使用对象

In brief, you should use an Object:

var data = {};
data[year] = "some data";

// or
var data = {
  2009: "2009 data",
  2010: "2010 data"
};

现在我回答这个问题的标题:是否JavaScript的填充空数组项

Now I answer the question title: "Does JavaScript populate empty array items?"

没有,正如我之前所说的,只有长度属性更改,(如果需要的话,只要加入该指数比目前更大的长度),长度递增到比指数的数值多了一个。

No, as I said before, only the length property is changed, (if necessary, only if the index added is larger than the current length), length is incremented to be one more than the numeric value of that index.

Array.prototype 方法的工作假设数组对象将其索引从零开始。

The Array.prototype methods work assuming that the array object will have its indexes starting from zero.

在previous指标并不真正存在于阵列对象,你可以测试一下:

The previous indexes don't really exist in the Array object, you can test it:

var array = [];
array[10] = undefined;

array.hasOwnProperty(10); // true
array.hasOwnProperty(9);  // false

总之,阵列意味着包含连续的索引,从0开始,如果你的属性不符合这些要求,你只需要使用一个对象。

In conclusion, arrays are meant to contain sequential indexes, starting from zero, if your properties don't meet those requirements, you should simply use an object.

这篇关于是否JavaScript的填充空数组项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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