日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【ES6(2015)】Function函数

發(fā)布時(shí)間:2025/3/15 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【ES6(2015)】Function函数 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

文章目錄

  • 1. 默認(rèn)參數(shù)
  • 2. Rest 參數(shù)
  • 3. 擴(kuò)展運(yùn)算符
  • 4. length屬性
  • 5. name屬性
  • 6. 箭頭函數(shù)

1. 默認(rèn)參數(shù)

ES5 的時(shí)候大家都會(huì)這么寫:

function foo(x, y) {y = y || 'world'console.log(x, y) } foo('hello', 'imooc') foo('hello', 0)

ES6中可以把默認(rèn)參數(shù)寫在參數(shù)列表:

function foo(x, y = 'world') {console.log(x, y) } foo('hello', 0)

函數(shù)參數(shù)是從左到右解析,如果沒有默認(rèn)值會(huì)被解析成 undefined

在ES6中我們不僅可以給參數(shù)默認(rèn)賦值具體的數(shù)值,同時(shí)參數(shù)賦值支持參數(shù)的邏輯運(yùn)算進(jìn)行賦值:

function f(x, y = 7, z = x + y) {return z * 0.5 }console.log(f(1, 7)) // 4

2. Rest 參數(shù)

function sum(...nums) {let num = 0nums.forEach(function(item) {num += item * 1})return num }console.log(sum(1, 2, 3)) // 6 console.log(sum(1, 2, 3, 4)) // 10

當(dāng)然,Rest Parameter 也可以和其他參數(shù)一起來用,比如:

function sum(base, ...nums) {let num = basenums.forEach(function(item) {num += item * 1})return num }console.log(sum(30, 1, 2, 3)) // 36 console.log(sum(30, 1, 2, 3, 4)) // 40

Rest 參數(shù)只能有一個(gè),且必須在參數(shù)列表的最后面。

3. 擴(kuò)展運(yùn)算符

Spread Operator 和 Rest Parameter 是形似但相反意義的操作符,簡單的來說 Rest Parameter 是把不定的參數(shù)“收斂”到數(shù)組,而 Spread Operator 是把固定的數(shù)組內(nèi)容“打散”到對(duì)應(yīng)的參數(shù)。示例如下:

function sum(x = 1, y = 2, z = 3) {return x + y + z }console.log(sum(...[4])) // 9 console.log(sum(...[4, 5])) // 12 console.log(sum(...[4, 5, 6])) // 15

4. length屬性

函數(shù)指定了默認(rèn)值以后,函數(shù)的length屬性,將返回沒有指定默認(rèn)值的參數(shù)個(gè)數(shù)。

function foo(x = 1, y = 2, z = 3) {console.log(x, y) } console.log(foo.length) // 0

5. name屬性

函數(shù)的name屬性,返回該函數(shù)的函數(shù)名。

function foo() {}foo.name // "foo"

6. 箭頭函數(shù)

// 定義函數(shù) function hello() {console.log('say hello') } // 或 let hello = function() {console.log('say hello') }// 使用箭頭函數(shù) let hello = () => {console.log('say hello') }

帶參數(shù)箭頭函數(shù):

let hello = (name) => {console.log('say hello', name) } // 或者let hello = name => {console.log('say hello', name) }

如果只有一個(gè)參數(shù),可以省略括號(hào),如果大于一個(gè)參數(shù)一定要記得帶括號(hào)。

如果返回值是表達(dá)式可以省略 return 和{}:

let pow = x => x * x

如果返回值是字面量對(duì)象,一定要用小括號(hào)包起來:

let person = (name) => ({age: 20,addr: 'Beijing City' })

1、箭頭函數(shù)中this指向定義時(shí)所在的對(duì)象,而不是調(diào)用時(shí)所在的對(duì)象
2、箭頭函數(shù)不可以當(dāng)作構(gòu)造函數(shù)
3、箭頭函數(shù)不可以使用arguments對(duì)象

創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)

總結(jié)

以上是生活随笔為你收集整理的【ES6(2015)】Function函数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。