一看就懂,代码如下:
<script>
console.log("=======1.数组的解构=======");
const DOG_NAMES = ['麦兜','泡泡','贝塔'];
let [mai,pao,bei] = DOG_NAMES;
console.log(mai); //麦兜
console.log(pao); //泡泡
console.log(bei); //贝塔
console.log("\n\n\n\n=======2.对象的解构=======");
const dog_1 = {
dogName:'麦兜',
dogAge:3,
dogKind:'边牧',
dogSex:'女',
dogPlayGames:function(){
console.log('狗狗超级爱玩球。。。。');
}
}
/**
* a. 对象解构的时候,属性名要和上面声明的对象里的属性名一致
* b. 即:相当于声明了几个变量,并对新声明的变量进行了赋值
*/
let {dogName,dogAge,dogPlayGames} = dog_1;
console.log(dogName);
console.log(dogAge);
// dog_1.dogPlayGames();
dogPlayGames();
</script>
效果如下:
const dog_1 = {
dogName:'麦兜',
dogAge:3,
dogKind:'边牧',
dogSex:'女'
}
let {dogName:dName,dogAge} = dog_1;//dogName 改成 dName
console.log(dName);
如下:
const dog_1 = {
dogName:'麦兜',
dogAge:3,
dogKind:{
kindId:'A1',
kindName:'边牧'
}
}
// let {dogName:dName,dogAge} = dog_1;
// let {dogKind} = dog_1;
// console.log(dogKind);
// console.log(dogKind.kindName);
let {dogKind:{kindId:kId,kindName}} = dog_1; //连续解构赋值
console.log(kId);
console.log(kindName);
<script>
function sum_1(x,y,z){
console.log(arguments);
return x + y + z;
}
const numbers = [1,2,3];
let result_1 = sum_1(...numbers);//等价于 let result_1 = sum_1(1,2,3);
console.log('result_1--->'+result_1);
</script>
var arr_1 = ['麦兜','贝塔','泡泡'];
var arr_2 = [...arr_1]; //数组拷贝
console.log(arr_2);
arr_2.push('西瓜');
console.log(arr_2);
let dogs = ['麦兜','贝塔','泡泡'];
let cats = ['猫咪1','猫咪2'];
let pets_1 = dogs.concat(cats); //使用函数 concat 连接
let pets_2 = [...dogs,...cats]; //使用扩展运算符连接
代码如下:
console.log('\n\n\n\n=============拷贝对象===========');
let user_1 = {name:'小花',age:18};
let user_2 = {...user_1};
user_2.name = '小明';
console.log(user_1);
console.log(user_2);
console.log('\n\n\n\n=============拷贝对象多层===========');
let pserson_1 = {
name:'小花',
age:18,
schoolInfo:{
schoolId:1001,
schoolName:'XXX第一高级中学'
}
}
let person_2 = {...pserson_1};
person_2.name = '小刚';
person_2.schoolInfo.schoolName = '第二中学';
console.log(pserson_1);
console.log(person_2);
效果如下:
let school_1 = {name:'北京大学',address:'北京'};
let school_2 = {...school_1,name:'清华大学',createDate:'1911'}; //在copy时,修改属性以及添加属性
var obj1 = { foo: "bar", x: 42 };
var obj2 = { foo: "baz", y: 13 };
var mergedObj = { ...obj1, ...obj2 };
// 合并后的对象:{ foo: "baz", x: 42, y: 13 }
jsx
(babel
)来展开:
<script type="text/babel">
//1. 创建组件
class DogComponent extends React.Component{
render(){
const {dogName,dogAge,dogKind,dogDesc} = this.props;//对象的解构赋值
return(
<ul>
<li>姓名:{dogName}</li>
<li>年龄:{dogAge}</li>
<li>种类:{dogKind}</li>
<li>备注:{dogDesc}</li>
<li>备注-2:{this.props.dogDesc}</li>
</ul>
)
}
}
//2. 定义对象
const dog ={
dogName:'麦兜',
dogAge:3,
dogKind:'边牧',
dogDesc:'温柔、撒娇、粘人、偶尔调皮~'
}
//3. 渲染组件到页面
ReactDOM.render(<DogComponent {...dog}/>,document.getElementById('dog'));
</script>