课程: JavaScript: Best Practices for Data

今天就学习课程吧!

今天就开通帐号,24,700 门业界名师课程任您挑!

Create arrays and objects using literals

Create arrays and objects using literals

- [Instructor] My code creates a new array using the array constructor, and passing in the array values as arguments. Likewise, it creates a new empty object using the object constructor. This is perfectly valid JavaScript, but stylistically, these constructors are often not the best choice. Because the array constructor accepts either a numeric argument for the number of elements or a comma separated list of values, there's a pitfall. If I want to create an empty array, I can use new array and pass the value zero. Or, if I want to create an array with some numbers in it, I can pass those as comma separated values. But if I want to create an array with a single element whose value is a number, then relying on the array constructor can have an unexpected outcome. For this reason, and for conciseness, most developers prefer to rely on the array literal, saving the constructor only for creating sparse arrays that need to…

内容