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

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

问题描述

我刚刚学习 JavaScript,似乎有很多方法可以声明数组.

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

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

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

var badArray = new Array(10);//创建一个大小为 10 个元素的空数组var goodArray= [10];//创建一个以 10 作为第一个元素的数组

<块引用>

正如你所看到的,这两行做了两件截然不同的事情.如果你本来想添加多个项目然后 badArray 将是正确初始化,因为 Javascript 将足够聪明知道您正在初始化数组而不是说明有多少您要添加的元素.

作者想说的是 Array(10) 创建一个包含 10 个元素的数组,而 [10] 创建一个包含第 0 个元素的未定义大小的数组10 岁?或者这是什么意思?

解决方案

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

function Array() { return [];}警报(数组(1、2、3));//一个空的警告框

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

function fetchValue(n) {var arr = new Array(1, 2, 3);返回 arr[n];}

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

var arr = new Array(1);

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]

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

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.

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?

解决方案

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];
}

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天全站免登陆