数组大小如何在Javascript中工作 [英] How do array sizes work in Javascript

查看:60
本文介绍了数组大小如何在Javascript中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中,如果将数组设置为大小为5( var foo = new Array(5); ),这只是初始大小吗?可以在创建后扩展元素数量。是否有可能做这样的事情 - arr = new Array()然后只是逐个分配元素?在此先感谢: - )

In JavaScript, if you set an array to be of size 5 ( var foo = new Array(5); ), is this just an initial size? Can you expand the number of elements after it is created. Is it possible to do something like this as well - arr = new Array() and then just assign elements one by one? Thanks in advance :-)

推荐答案

是的,它只是一个初始大小,并不是必需的。如果你不使用一个数字,你可以立即填充。

Yes it is just an initial size, and it is not required. If you don't use a single number, you can immediately populate.

使用更简单的 [] 语法。

var arr = ['something', 34, 'hello'];

您可以使用括号设置(或替换)特定索引:

You can set (or replace) a specific index by using brackets:

arr[0] = "I'm here replacing whatever your first item was";

您可以使用push添加到最后:

You can add to the end by using push:

arr.push('add me');

如果您这样做,可能会在某些浏览器中获得更快的性能:

There may be faster performance in some browsers if you do it like this instead:

arr[arr.length] = 'add me';

您可以在任何索引处添加内容。

You can add something at any index.

您可以使用拼接完全删除项目:

You can remove an item completely using splice:

arr.splice(0, 1); // remove first item in the array (start at index 0, with 1 being removed)

这篇关于数组大小如何在Javascript中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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