解构:
JS 的结构很灵活:参考
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Spread_syntax
列表解构
参数解构
数组解构
结构的时候,变量从左到右和元素对齐,可变参数放到最右边
能对应到数据就返回数据,对应不到数据,返回默认值,没有默认值,就返回undefined
对象解构
解构时,需要提供对象的属性名,会根据属性名找到对应的值,没有找到的返回缺省值,没哟缺省值的,返回undefined
复制解构
数组
对象:
数组的操作:
测试:
1 const arr = [1,2,3,4,5] 2 arr.push(6,7) 3 console.log(arr) 4 5 console.log(arr.pop()) 6 console.log(arr) 7 8 console.log('================ map =================') 9 // map 返回一个新数组 10 const p = arr.map(x => x*x); 11 console.log(p) 12 console.log('================ forEach =================') 13 14 // forEach 没有返回值 15 const newarr = arr.forEach(x => x + 10) 16 console.log(newarr, arr) 17 console.log('------------------------------------------') 18 narr =[] 19 Arr = arr.forEach(x => narr.push(x +1)); 20 console.log(Arr, narr) 21 console.log('------------------------------------------') 22 23 var newarr1 = [] // 不需要for了 24 console.log(arr.forEach(x => { 25 newarr1.push(x * 2) 26 })) 27 console.log(newarr1) 28 console.log('------------------------------------------') 29 30 var newarr2 = [] // 不需要for了 31 console.log(arr.forEach( (x,y,z) => { 32 console.log(x) // value 33 console.log(y) // index 34 console.log(z) // arr 35 newarr2[y] = x * 2 36 })) 37 38 console.log('================ filter =================') 39 40 // filter 返回新数组 41 var ARR = arr.filter(x => x%2==0) 42 console.log(ARR)
结果:
1 Info: Start process (19:56:39) 2 [ 1, 2, 3, 4, 5, 6, 7 ] 3 7 4 [ 1, 2, 3, 4, 5, 6 ] 5 ================ map ================= 6 [ 1, 4, 9, 16, 25, 36 ] 7 ================ forEach ================= 8 undefined [ 1, 2, 3, 4, 5, 6 ] 9 ------------------------------------------ 10 undefined [ 2, 3, 4, 5, 6, 7 ] 11 ------------------------------------------ 12 undefined 13 [ 2, 4, 6, 8, 10, 12 ] 14 ------------------------------------------ 15 1 16 0 17 [ 1, 2, 3, 4, 5, 6 ] 18 2 19 1 20 [ 1, 2, 3, 4, 5, 6 ] 21 3 22 2 23 [ 1, 2, 3, 4, 5, 6 ] 24 4 25 3 26 [ 1, 2, 3, 4, 5, 6 ] 27 5 28 4 29 [ 1, 2, 3, 4, 5, 6 ] 30 6 31 5 32 [ 1, 2, 3, 4, 5, 6 ] 33 undefined 34 ================ filter ================= 35 [ 2, 4, 6 ] 36 Info: End process (19:56:40)