原生JS---解构赋值
好久没写博客了,惭愧惭愧。。。。。。今天来看一下解构赋值。
解构赋值语法是一种JavaScript表达式,它使得将值从数组、或属性从对象,提取到不同的变量中,成为可能。
(一)解构数组
1.1 变量声明并赋值
var foo = ["one", "two", "three"]; var [one, two, three] = foo; console.log(one); // "one" console.log(two); // "two" console.log(three); // "three"
1.2 变量先声明后赋值时的解构
var a,b; [ a,b ] = [ 1,2 ]; console.log(a) //1 console.log(b) //2
1.3 默认值:为防止从数组重取出一个值为undefined的对象,可以再表达式左边的数组中为任意对象预设为默认值
var a,b; [a = 5,b = 7] = [1]; console.log(a) //1 console.log(b) //7
1.4 解析函数的返回值---数组
function f(){ return [1,2,3,4]; } [x,y,...z] = f(); console.log(x) // 1 console.log(y) //2 console.log(z) // Array(2) [3,4]
1.5 忽略某些返回值
function f() { return [1, 2, 3, 4]; } [x,, ...z] = f(); console.log(x) // 1 console.log(z) // Array(2) [3,4]
1.6 将剩余数组赋值给一个变量(当解构一个数组时,可以使用剩余模式,将数组剩余部分赋值给一个变量)
!!注意:剩余元素右侧不可有逗号,不然会抛出一个错误
var [a,...b] = [1,2,3] console.log(a) // 1 console.log(b) // [2,3]
(二)解构对象
2.1 基本赋值
var o = {p:1,q:true}; var {p,q} = o; console.log(p) // 1 console.log(q) //true
2.2 无声明赋值
var a,b; ({a,b} = {a:1,b:2}) console.log(a) // a console.log(b) // b
2.3 给新的变量名赋值(我们可以从一个对象中提取变量并赋值给和对象属性名不同的新的变量名)
var o = {p:1,q:false} var {p:bar,q:foo} = o; console.log(bar) //1 console.log(foo) //false
2.4默认值(变量可以先赋予相应的默认值。当腰提取的对象没有相应的属性时,变量就会被赋予默认值)
var {a = 10,b = 5} = { a:3}; console.log(a) // 3 console.log(b) //3
2.5给新的变量命名并提供默认值
var {a:aa = 10,b:bb=100} = {a:3}; console.log(aa) //3 console.log(bb) //100
2.6函数参数默认值
function drawES2015Chart({size = 'big', cords = { x: 0, y: 0 }, radius = 25} = {}) { console.log(size, cords, radius); // do some chart drawing } drawES2015Chart({ cords: { x: 18, y: 30 }, radius: 30 });
如果你忽略了右边的赋值,那么函数会在被调用的时候查找至少一个被提供的参数,而在当前的形式下,你可以直接调用
drawES2015Chart()
而不提供任何参数。
2.7解构嵌套对象和数组
const metadata = { title: 'Scratchpad', translations: [ { url: '/de/docs/Tools/Scratchpad', title: 'JavaScript-Umgebung' } ], url: '/en-US/docs/Tools/Scratchpad' }; let { title: englishTitle, // rename translations: [ { title: localeTitle, // rename }, ], } = metadata; console.log(englishTitle); // "Scratchpad" console.log(localeTitle); // "JavaScript-Umgebung"
2.8 For of 迭代和解构
var people = [ { name: 'Mike Smith', family: { mother: 'Jane Smith', father: 'Harry Smith', sister: 'Samantha Smith' }, age: 35 }, { name: 'Tom Jones', family: { mother: 'Norah Jones', father: 'Richard Jones', brother: 'Howard Jones' }, age: 25 } ]; for (var {name: n, family: {father: f}} of people) { console.log('Name: ' + n + ', Father: ' + f); } // "Name: Mike Smith, Father: Harry Smith" // "Name: Tom Jones, Father: Richard Jones"
每天进步一点点!!