>[success] # 创建数组 ~~~ 1.在es5中创建数组,有两种方法一种是字面量的创建,一种是构造函数的创建, 在es6多了一种'Array.of()'方法 ~~~ >[danger] ##### es5 的创建数组 ~~~ 1.使用构造函数创建的问题是,如果传入一个数值型的值,数组长度会变成该值, 如果传入的是非数字 或者是多项内容,则会将这些内容变成数组的元素 ~~~ ~~~ const array = [1,2,3,4,5] // 构造函数创建 const array1 = new Array(1) const array2 = new Array('1') const array3 = new Array(1,2) const array4 = new Array(1,'1') console.log(array) // [1, 2, 3, 4, 5] console.log(array1) // [empty] 注释:长度为1 内容空 console.log(array2) // ["1"] console.log(array3) // [1, 2] console.log(array4) // [1, "1"] ~~~ >[danger] ##### es6 -- Array.of ~~~ 1.不管你传入啥最后都是改生成数组的元素,理解成构造函数的升级版本 ~~~ ~~~ const array = Array.of(1) console.log(array) // [1] ~~~ >[success] # 转换数组 -- Array.from [mdn关于from](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/from) ~~~ 1.Array.from() 可以通过以下方式来创建数组对象: 伪数组对象(拥有一个 length 属性和若干索引属性的任意对象) 可迭代对象(可以获取对象中的元素,如 Map和 Set 等) 2.简单粗暴的理解和 '[...Array ]'类似,但是Array.from() 可以接受回调因此可扩展性更高,并且 展开运算符对' {0:1,1:'1',length:2}'这种对象形式数组是无法解析的,但是对'arguments'这种伪数组 是可以转换的 3.`Array.from(obj, mapFn, thisArg)`就相当于`Array.from(obj).map(mapFn, thisArg)` ~~~ >[danger] ##### 伪数组对象 * es5 将伪数组转成数组(案例一) ~~~ function test() { console.log([].slice.call(arguments)) //  [1, 2, 3, 4] console.log(Array.prototype.slice.call(arguments)) //  [1, 2, 3, 4] } test(1,2,3,4) ~~~ * es5 将伪数组转成数组(案例二) ~~~ var obj = {0:1,1:'1',length:2} console.log(Array.prototype.slice.call(obj)) // [1,"1"] ~~~ * es6 -- Array.from ~~~ var obj = {0:1,1:'1',length:2} console.log(Array.from(obj)) // [1,"1"] function test() { console.log(Array.from(arguments)) //  [1, 2, 3, 4] console.log([...arguments]) //  [1, 2, 3, 4] } test(1,2,3,4) ~~~ >[danger] ##### 可迭代对象 ~~~ 1.因此其他的可迭代对象都可以用Array.from生成一个新的数组, 例如'map' 和'set' ~~~ ~~~ function *test() { yield 1 yield 2 yield 3 } console.log(Array.from(test())) // [1,2,3] console.log([...test()]) // [1,2,3] let test1= { *[Symbol.iterator](){ yield 1 yield 2 yield 3 } } console.log(Array.from(test1)) // [1,2,3] console.log([...test1]) // [1,2,3] ~~~ >[danger] ##### Array.from 第二个参数回调函数 ~~~ Array.from([1, 2, 3], x => x + x); // x => x + x代表这是一个函数,只是省略了其他的定义,这是一种Lambda表达式的写法 // 箭头的意思表示从当前数组中取出一个值,然后自加,并将返回的结果添加到新数组中 // [2, 4, 6] //生成一个数字序列 //由于数组在每个位置上都以' undefined '进行初始化, //下面的' v '值为' undefined ' Array.from({length: 5}, (v, i) => i); // [0, 1, 2, 3, 4] ~~~ >[danger] ##### 对回调中的参数做解释 ~~~ 1.通过下面案例可以看出来,回调的第一个参数是数组循环对应的项,第二个参数是对应循环的下角标 ,下面第二个案例可以发现因为不是一个理论上的纯数组,此时认为你长度为5,每个内容都为'undefind' ~~~ ~~~ const test = Array.from(['a','b','c'],(v,i)=>{ /* a 0 b 1 c 2 */ console.log(v,i) return i }) console.log(test)// [ 0, 1, 2 ] const test1 = Array.from({length:3},(v,i)=>{ /* undefined 0 undefined 1 undefined 2 */ console.log(v,i) return i }) console.log(test1) // [ 0, 1, 2 ] ~~~