什么是 javascript 中的数组文字表示法,什么时候应该使用它? [英] What is array literal notation in javascript and when should you use it?
问题描述
JSLint 给了我这个错误:
<块引用>第 11 行字符 33 的问题:使用数组文字表示法 [].
var myArray = new Array();
什么是数组字面量表示法,为什么要我用它来代替?
它在这里显示 new Array();
应该可以正常工作......有什么我遗漏的吗?
数组文字表示法是您仅使用空括号定义新数组的地方.在您的示例中:
var myArray = [];
这是定义数组的新"方式,我想它更短/更干净.
下面的例子解释了它们之间的区别:
var a = [],//这些都是一样的b = new Array(),//a 和 b 是长度为 0 的数组c = ['foo', 'bar'],//这些都是一样的d = new Array('foo', 'bar'),//c 和 d 是有 2 个字符串的数组//这些是不同的:e = [3],//e.length == 1, e[0] == 3f = 新数组(3);//f.length == 3, f[0] == 未定义
<块引用>
参考:声明 JavaScript 时Array()"和[]"有什么区别数组?
JSLint is giving me this error:
Problem at line 11 character 33: Use the array literal notation [].
var myArray = new Array();
What is array literal notation and why does it want me to use it instead?
It shows here that new Array();
should work fine... is there something I'm missing?
array literal notation is where you define a new array using just empty brackets. In your example:
var myArray = [];
It is the "new" way of defining arrays, and I suppose it is shorter/cleaner.
The examples below explain the difference between them:
var a = [], // these are the same
b = new Array(), // a and b are arrays with length 0
c = ['foo', 'bar'], // these are the same
d = new Array('foo', 'bar'), // c and d are arrays with 2 strings
// these are different:
e = [3], // e.length == 1, e[0] == 3
f = new Array(3); // f.length == 3, f[0] == undefined
Reference: What’s the difference between "Array()" and "[]" while declaring a JavaScript array?
这篇关于什么是 javascript 中的数组文字表示法,什么时候应该使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!