ES6 解構賦值

2021-09-29 14:29:54 字數 3216 閱讀 5280

物件模型的解構(object)

字串擴充套件

函式擴充套件

var宣告變數存在預解析

允許重複宣告

console.log(flag);

var flag = true;

let宣告變數不存在預解析

宣告變數不允許重複(在同一作用域)

在es6 一定要注意先宣告再使用

/*if (true) 

*/ for (let i = 0; i < 10; i++)

console.log(i);

const

用來宣告變數(π,e)

不允許重新賦值

宣告變數必須初始化

解構賦值是對賦值運算子的擴充套件。

他是一種針對陣列或者物件進行模式匹配,然後對其中的變數進行賦值。

let [a, b, c] = [1, 2, 3];
let [a, [[b], c]] = [1, [[2], 3]];
let [a, , b] = [1, 2, 3];
let [a = 1, b] = ;

// a = 1, b = undefined

let [a, ...b] = [1, 2, 3];

//a = 1

//b = [2, 3]

let [a, b, c, d, e] = 'hello';

// a = 'h'

// b = 'e'

// c = 'l'

// d = 'l'

// e = 'o'

let [a = 2] = [undefined]; 

// a = 2

當解構模式有匹配結果,且匹配結果是 undefined 時,會觸發預設值作為返回結果。

let [a = 3, b = a] = ;     // a = 3, b = 3

let [a = 3, b = a] = [1]; // a = 1, b = 1

let [a = 3, b = a] = [1, 2]; // a = 1, b = 2

物件的本質是一系列無規則的鍵值對

//物件的解構賦值

/*let = ;

console.log('obj1 ' + obj1);

console.log('obj2 ' +obj2);*/

//物件的屬性別名 注意:起了別名之後 原來的名字就無效了

// let = ;

// console.log('obj1 ' + john);

// console.log('obj2 ' +obj2);

//物件的解構賦值中 也可以指定預設值

// let = ;

// console.log('obj1 ' + john);

// console.log('obj2 ' +obj2);

//math是內建物件 不需要例項化

/*console.log(math);

//let = ;

let = math; // , cos:funciton(){} }

console.log(random);

console.log(sin);

console.log(cos);*/

傳統的方法 indexof

var str = "seven jack dijia tailuo rio";

console.log(str.includes('jack',7));

console.log(str.startswith('jack'));

console.log(str.endswith(' rio '));

模版字串 用反引號(`)標識,資料用${}進行填充

let obj = 

let tag = "name:" + obj.name +"

"; let temp = `

$$$`

console.log(temp);

引數預設值

function fun(param) 

fun('hi');

function fun1(param="how")

fun1();

引數解構賦值

function fun1( = {}) 

fun1();

// =

fun1();

rest引數

function fun2(a,b,c,...para) 

fun2(1,2,3,4,5,6,7)

擴充套件運算子

function fun(a,b,c,d) 

fun(1,2,3,4);

let arr = [1, 2, 3, 4];

fun(...arr);

箭頭函式

es6允許使用「箭頭」(=>)定義函式。

var f = v => v;

//上面的箭頭函式等同於:

var f = function(v) ;

如果箭頭函式不需要引數或需要多個引數,就使用乙個圓括號代表引數部分。

var f = () => 5;

// 等同於

var f = function () ;

var sum = (num1, num2) => num1 + num2;

// 等同於

var sum = function(num1, num2) ;

如果箭頭函式的**塊部分多於一條語句,就要使用大括號將它們括起來,並且使用return語句返回。

var sum = (num1, num2) =>
由於大括號被解釋為**塊,所以如果箭頭函式直接返回乙個物件,必須在物件外面加上括號。

var gettempitem = id => ();

ES6 解構賦值

陣列的解構賦值 let a,b 12,13 let a,b,c d 13,15,16 let a,b c 78,12 23 let x,y 1,3,5 x 1,y 3 let x,y,z a x a,y undefined z let h,b 1,2,3,4 1,2,3,4 預設值 let x tr...

ES6解構賦值

一 基本用法 解構 destructuring 按照一定的模式,從陣列或者物件中提取值,對變數進行賦值。let par1,par2,par3 1,2 console.log par1,par2,par3 1 2 不完全解構時par3對值為undefined 解構賦值允許指定變數對預設值。let pa...

es6解構賦值

coding changes the world accumulating makes yourself 主要從三個方面講述 陣列式的解構賦值 物件式的解構賦值 函式中的解構賦值 preface 現今的變數宣告語法十分的直接 左邊是乙個變數名,右邊可以是乙個陣列 的表示式或乙個物件 的表示式,等等。...