【ES6(2015)】Function函数
文章目錄
- 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)) // 42. 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)) // 40Rest 參數(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])) // 154. 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) // 05. 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ì)象
總結(jié)
以上是生活随笔為你收集整理的【ES6(2015)】Function函数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 判断作弊 牛客 编程_牛客企业服务产品-
- 下一篇: [1] SDK Tools安装