-
new 一个
let colors = new Array () // [] let colors = new Array (20) // 创建一个 length = 20 的数组 let colors = new Array ('red','cyan','pink') // ['red','cyan','pink']
-
不使用new
let colors = Array () // [] let colors = Array (20) // 创建一个 length = 20 的数组 let colors = Array ('red','cyan','pink') // ['red','cyan','pink']
-
字面量 // 数组的字面量方式创建数组时,和 Object 一样不会执行 Array 的构造函数
let colors = [ ] let colors = ['red','cyan','pink']
-
ES6 新增的 from()
4.1Array.from()的第一个参数是一个类数组对象,或者一个有 length 属性和可索引元素的结构Array.from('Matt') // ['M','a','t','t'] const m = new Map().set(1,2).set(3,4) // {1=>2,3=>4} Array.from(m) // [[1,2],[3,4]] const s = new Set().add(1).add(2).add(3).add(4) // {1,2,3,4} Array.from(s) // [1,2,3,4]
4.2、可以对现有数组进行复制const a1 = [1,2,3,4] const a2 = Array.from(a1)// [1,2,3,4] console.log(a1 === a2) // false
4.3、 arguments 对象可以被轻松转换为数组function fn(){ return Array.form(arguments) } console.log(fn(1,2,3,4)) // [1,2,3,4]
4.4、 Array.from() 也能转换带有必要属性的自定义对象const obj={ 0:1, 1:2, 2:3, 3:4, length:4 } console.log(Array.from(obj)) // [1,2,3,4]
4.5、 Array.from() 还可以接收第二可选的映射函数参数const a1=[1,2,3,4] console.log(Array.from(a1,x=>x**2))//[1,4,9,16]
-
Array.of() 可以把一组参数转换为数组,这个方法用于替换 ES6 之前常用的 Array.prototype.slice.call(arguments),一种异常笨拙的将arguments对象转成数组的写法
console.log(Array.of(1,2,3,4)) // [1,2,3,4]
创建数组
最新推荐文章于 2022-06-09 18:23:26 发布