(3)ES6解构赋值-对象篇

对象的解构赋值(可以不按顺序,但是key必须一样否则为undefined)

//demo1
var {name,age} = { name: "Jewave", age:26 };
console.log(name); //'jewave'
console.log(age); // //demo2
var {id,name,age} = { name: "Jewave", age:26,id:007 };
console.log(name); //'jewave'
console.log(age); //
console.log(id) // //demo3
var { id: personId, name: personName, age: personAge } = { name: "Jewave", age:26,id:007 };
console.log(personId); //
console.log(personName); //'jewave'
console.log(personAge); // //demo4
let object = { first: 'Hello', last: 'World' };
let { first: firstName, last: lastName } = object;
console.log(firstName); //Hello
console.log(lastName); //World

对象解构默认值的条件(对象属性值严格等于undefined,也就是未定义)

//demo1
var { x = 3 } = {};
console.log(x); // //demo2
var { x, y = 5 } = { x: 1 };
console.log(x); //
console.log(y); // //demo3
var { message: msg = "You Are A Person!" } = {};
consle.log(msg); //"You Are A Person!" //demo4
var { x = 3 } = { x: undefined };
console.log(x); // //demo5
var { y = 3 } = { y: null };
console.log(y);//null

已声明变量的解构赋值

var x;
{x} = { x: 1 }; // Uncaught SyntaxError: Unexpected token =
为啥报错,因为{x}被理解成代码块而不是对象所以不能进行解构,
这时候我们用一个括号将整体括起来就可以。 var x;
({x} = { x: 1 });
console.log(x); //

现有对象的方法

console.log( Math.sin(Math.PI/6) ); //0.49999999999999994

//简化版的写法可读性更棒
let { sin, cos, tan, cot, PI } = Math;
console.log( PI ); //3.141592653589793
console.log( sin(PI/6) ); //0.49999999999999994
上一篇:Hibernate三大类查询总结


下一篇:关于ConcurrentSkipListMap的理解