只需添加元素即可更改数组大小,无需推送javascript [英] Change array size by just adding element and no push javascript

查看:73
本文介绍了只需添加元素即可更改数组大小,无需推送javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道更改数组大小的通用方法是使用 .push()

I know the universal way of changing an array's size is to use .push().

但是,今天我看到angularJS中的一段代码做了这样的事情:

However, today I saw a piece of code in angularJS that does something like this:

var service = {
   pages: [],
   doSmth: doSmth
};

doSmth();

function doSmth() {
   service.pages[1] = "abc";
   service.pages[5] = "def";
}

我在浏览器上运行调试器,发现在 doSmth(), pages [1] 未定义,但在此之后, pages [1] 被赋值没有任何错误。

I ran the debugger on the browser and found that before doSmth() is called, pages[1] is undefined, but after that, pages[1] is assigned the value without any error.

这怎么可能?

推荐答案

这就是JavaScript允许的魔力。如果你来自Java或C这样的语言,这可能看起来像一个奇怪的想法,但你可以随时设置数组中任何索引的值,并且数组将扩展到那个大小!

That's just the magic that JavaScript allows. If you come from a language like Java or C, this may seem like a weird idea, but you can set the value of any index in the array at any time, and the array will expand to that size!

考虑:

var t = [];
t.length === 0;
t[10000] = 'value';
t.length === 10001;

JavaScript只是在幕后处理这个问题。值得一提的是,这种行为并非特定于JavaScript。在其他解释语言中也可以看到这一点。例如,Ruby允许您执行相同的操作。

JavaScript just handles this behind the scenes. It's worth mentioning that this behavior is not specific to JavaScript. This is seen a bit in other interpreted languages as well. Ruby, for example, allows you to do the same.

此外,在JavaScript中, length 是数组的可写属性,因此您可以轻松截断或清除整个数组:

Additionally in JavaScript, length is a writeable attribute of arrays, so you can easily truncate or clear an entire array:

var t = [1];
t[4] = 0;
t === [1, undefined, undefined, undefined, 0];
t.length = 2;
t === [1, undefined];
t.length = 0;
t === [];

将长度设置为0是清除数组的最快速,最简单的方法之一。它可能不是最直观的解决方案,但它是我的首选。

Setting the length to 0 is one of the fastest and simplest ways to clear an array. It might not be the most intuitive solution, but it's my go-to.

这篇关于只需添加元素即可更改数组大小,无需推送javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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