4

es6语法学习

 3 years ago
source link: https://segmentfault.com/a/1190000040475763
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

es6语法学习

题外话:很久没有更新了,这几天学习react.js的时候学习了一些新的东西,记录下。
1、解构赋值
字面上的意思:要根据对象的结构进行一一对应的赋值。
(1)、普通变量

//ES5
let a = 1, b = 2;
//(ES6)
let [a, b] = [1,2]; 

位置一一对应,就可以赋值了。
(2)、数组

let a = [1,2,3]; (ES5)
let num = a[2]; console.log( num);  // 3

let [a,b,c] = [1,2,3];   (ES6)
console.log(b); //2

嵌套数组解构

let a = [1,2, [3,4],5]; 
let num = a[2][0]; // 3

let [a, b,[c,d],e] =  [1,2, [3,4], 5] ;
console.log(b, c) // 2, 3

解构赋值的话如果解构不成功,变量的值就等于undefined。

let [a, b] = [1];
console.log(b) // undefined

有默认值,且没有值的,取默认值;
有值的取自身的值,不取默认值

let[a,b,c,d=4] = [1,2,3];
console.log(d);//4

let[a,b,c,d=4] = [1,2,3,5];
console.log(d);//5

对象的解构与数组有一个重要的不同。数组的元素是按次序排列的,变量的取值由它的位置决定;而对象的属性没有次序,变量必须与属性同名,才能取到正确的值。

let obj = { name: 'xxx',age: 18};
console.log(obj.name);//'xxx'

let obj = {name:"xxx",age:"18"}
let { name: name, age: age} = obj;
console.log( name);//'xxx'

如果解构失败,变量的值等于undefined。

let {foo} = {bar: 'baz'};
foo // undefined

字符串也可以解构赋值。这是因为此时,字符串被转换成了一个类似数组的对象。

// ES5:
var res = "你好呀";
console.log(res[2]);//呀

//ES6
let[a,b,c] = "你好呀";
console.log(b);//好

函数参数解构

function show({name,age}){
  //以前
  // var name = obj.name;
  //现在
  console.log(name);//李四
  console.log(name,age);//李四,18
}
let obj = {
  name:"李四",
  age:"18"
}
show(obj);

未完待续......

参考资料: https://zhuanlan.zhihu.com/p/...


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK