基于ES6作用域和解構(gòu)賦值詳解
ES6 強(qiáng)制開啟嚴(yán)格模式
作用域
•var 聲明局部變量,for/if花括號中定義的變量在花括號外也可訪問
•let 聲明的變量為塊作用域,變量不可重復(fù)定義
•const 聲明常量,塊作用域,聲明時必須賦值,不可修改
// const聲明的k指向一個對象,k本身不可變,但對象可變
function test() {
const k={
a:1
}
k.b=3;
console.log(k);
}
test()解構(gòu)賦值
{
let a, b, 3, rest;
[a, b, c=3]=[1, 2];
console.log(a, b);
}
//output: 1 2 3
{
let a, b, 3, rest;
[a, b, c]=[1, 2];
console.log(a, b);
}
//output: 1 2 undefined
{
let a, b, rest;
[a, b, ...rest] = [1, 2, 3, 4, 5, 6];
console.log(a, b, rest);
}
//output:1 2 [3, 4, 5, 6]
{
let a, b;
({a, b} = {a:1, b:2})
console.log(a ,b);
}
//output: 1 2
使用場景
變量交換
{
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a, b);
}
獲取多個函數(shù)值
{
function f(){
return [1, 2]
}
let a, b;
[a, b] = f();
console.log(a, b);
}
獲取多個函數(shù)返回值
{
function f(){
return [1, 2, 3, 4, 5]
}
let a, b, c;
[a,,,b] = f();
console.log(a, b);
}
//output: 1 4
{
function f(){
return [1, 2, 3, 4, 5]
}
let a, b, c;
[a, ...b] = f();
console.log(a, b);
}
//output: 1 [2, 3, 4, 5]
對象解構(gòu)賦值
{
let o={p:42, q:true};
let {p, q, c=5} = o;
console.log(p ,q);
}
//output: 42 true 5
獲取json值
{
let metaData={
title: 'abc',
test: [{
title: 'test',
desc: 'description'
}]
}
let {title:esTitle, test:[{title:cnTitle}]} = metaData;
console.log(esTitle, cnTitle);
}
//Output: abc test
以上這篇基于ES6作用域和解構(gòu)賦值詳解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
- 深入理解es6塊級作用域的使用
- ES6學(xué)習(xí)教程之塊級作用域詳解
- 深入理解ES6學(xué)習(xí)筆記之塊級作用域綁定
- ES6使用let命令更簡單的實(shí)現(xiàn)塊級作用域?qū)嵗治?/a>
- es6函數(shù)之rest參數(shù)用法實(shí)例分析
- es6函數(shù)之嚴(yán)格模式用法實(shí)例分析
- ES6學(xué)習(xí)筆記之字符串、數(shù)組、對象、函數(shù)新增知識點(diǎn)實(shí)例分析
- ES6知識點(diǎn)整理之函數(shù)對象參數(shù)默認(rèn)值及其解構(gòu)應(yīng)用示例
- ES6知識點(diǎn)整理之函數(shù)數(shù)組參數(shù)的默認(rèn)值及其解構(gòu)應(yīng)用示例
- 關(guān)于ES6箭頭函數(shù)中的this問題
- ES6中Array.includes()函數(shù)的用法
- es6函數(shù)中的作用域?qū)嵗治?/a>
相關(guān)文章
setInterval計(jì)時器不準(zhǔn)的問題解決方法
在js中如果打算使用setInterval進(jìn)行倒數(shù),計(jì)時等功能,往往是不準(zhǔn)確的,針對這個問題,本文有個不錯的解決方案2014-05-05
基于IE下ul li 互相嵌套時的bug,排查,解決過程以及心得介紹
JavaScript中常用的字符串方法函數(shù)操作方法總結(jié)
javascript版的in_array函數(shù)(判斷數(shù)組中是否存在特定值)
echarts堆疊柱狀圖柱子之間間隔開具體實(shí)現(xiàn)代碼
jQuery NProgress.js加載進(jìn)度插件的簡單使用方法

