[JavaScript] ES6 其他好用的新語法


Posted by Nicolakacha on 2020-09-05

以下零碎的記錄一些好用的 ES6 語法

呼叫函式時可以傳物件

function test({a, b}) {
    console.log(a)
}
test({
    a: 1
    b: 2
})

可在物件裡面引入別的變數

const name = "john snow";
const obj = {
    [name]: "hello";
    [1 + 2]: "hihi"
}

如果物件內的 key 和 value 一樣,可省略

const a = "Simon";
const b = true;
const c = {};
const obj = {a, b, c}

展開 Spread Operator

var arr = [1, 2, 3]
var arr2 = [4, 5, 6, ...arr]
console.log(arr2) // [4, 5, 6, 1, 2, 3]
var obj1 = {
    a: 1,
    b: 2
}

var obj2 = {
    z: 1
}

var obj3 = {
    ...obj1,
    c: 3
}

console.log(obj3) // 

a: 1
b: 2
c: 3

用來複製

arr1 = [1, 2, 3]
arr2 = [...arr1]

反向展開 Rest Parameters

var arr = [1, 2, 3, 4]
var [first, ...rest] = arr
console.log(rest) // [2, 3, 4, 5]
var obj = {
    a: 1, 
    b: 2,
    c: 3
}

var {a, ...obj2} = obj
console.log(a, obj2) // 1, {b: 2, c: 3}
function add(...args) {
    return a + b
}
console.log(add(1, 2))

預設值 Default Parameters

                         預設值
                            v
function repeat(str, times = 5) {
    return str.repeat(times)
}

console.log(repeat('abc'))
function greet(name='', age=30) {
    return `Hello ${name} you seem to be ${age-10}. What a lovely day`
}

箭頭函式 Arrow Function

如果是表達式

const callName = (someone) => '我是 ' + someone;

如果只有一個參數

const callName = someone => '我是 ' + someone;
const test = function test(n){return n}
const test = (n) => {return n}
var arr = [1, 2, 3, 4, 5]
console.log(
    arr
    .filter(function(value){
        return value > 1
    })
    .map(function(value){
        return value * 2
    })
)
------------------
arr
    .filter(value => value > 1)
    .map(value => value * 2)

#javascript #ES6







Related Posts

Python 字串和字元處理入門教學

Python 字串和字元處理入門教學

安裝 vim-devicons 檔案圖示

安裝 vim-devicons 檔案圖示

Advanced iOS App Architecture (Second Edition): Real-World App Architecture in Swift

Advanced iOS App Architecture (Second Edition): Real-World App Architecture in Swift


Comments