在JavaScript中声明数组的方式是什么? [英] What is the way of declaring an array in JavaScript?

查看:282
本文介绍了在JavaScript中声明数组的方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在学习JavaScript,似乎有很多方法来声明数组。

I'm just learning JavaScript and it seems like there are a number of ways to declare arrays.


  1. var myArray = new Array()

  2. var myArray = new Array(3)

  3. var myArray = [apples,bananas,oranges]

  4. var myArray = [3]

  1. var myArray = new Array()
  2. var myArray = new Array(3)
  3. var myArray = ["apples", "bananas", "oranges"]
  4. var myArray = [3]

它们有什么区别,有什么首选方式?

What are their difference, and what are the preferred ways?

根据本网站以下两行非常不同:

According to this website the following two lines are very different:

var badArray = new Array(10); // creates an empty Array that's sized for 10 elements
var goodArray= [10];          // creates an Array with 10 as the first element




尽可能看到这两行做了两件截然不同的事情。如果
想要添加多个项目,那么badArray将是
正确初始化,因为Javascript会足够聪明到
知道你正在初始化数组而不是说明多少$ b你要添加的$ b元素。

As you can see these two lines do two very different things. If you had wanted to add more than one item then badArray would be initialized correctly since Javascript would then be smart enough to know that you were initializing the array instead of stating how many elements you wanted to add.

作者试图说的是数组(10)创建一个包含10个元素的数组, [10] 创建一个未定义大小的数组,第0个元素为10?或者这意味着什么?

Is what the authors trying to say is Array(10) creates an array with precisely 10 elements and [10] creates an array of undefined size with the 0th element being 10? Or what does this mean?

推荐答案

首选方法是始终使用带方括号的文字语法;与 Array 的不同,它的行为可以预测任意数量的项目。更重要的是,数组不是一个关键字,虽然这不是一个现实的情况,但有人可以轻易地覆盖它:

The preferred way is to always use the literal syntax with square brackets; its behaviour is predictable for any number of items, unlike Array's. What's more, Array is not a keyword, and although it is not a realistic situation, someone could easily overwrite it:

function Array() { return []; }

alert(Array(1, 2, 3)); // An empty alert box

然而,更大的问题是一致性问题。有人重构代码可能遇到这个函数:

However, the larger issue is that of consistency. Someone refactoring code could come across this function:

function fetchValue(n) {
    var arr = new Array(1, 2, 3);

    return arr[n];
}

事实证明,只有 fetchValue(0) 是必需的,所以程序员会丢弃其他元素并破坏代码,因为它现在返回 undefined

As it turns out, only fetchValue(0) is ever needed, so the programmer drops the other elements and breaks the code, because it now returns undefined:

var arr = new Array(1);

这篇关于在JavaScript中声明数组的方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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