004. ES6之函数的扩展

1. 函数参数的默认值

ES6 允许为函数的参数设置默认值,

1function log(x, y = 'World') { 2 console.log(x, y); 3} 4 5log('Hello') // Hello World 6log('Hello', 'China') // Hello China 7log('Hello', '') // Hello 8 9// 1. 参数变量是默认声明的,所以不能用 let 或 const 再次声明 10function foo(x = 5) { 11 let x = 1; // error 12 const x = 2; // error 13} 14 15// 2. 使用默认值时,函数不能有同名参数 16 17// 3. 参数默认值不是传值的,而是每次都重新计算默认值表达式的值 18let x = 99; 19function foo(p = x + 1) { 20 console.log(p); 21} 22foo() // 100 23x = 100; 24foo() // 101

2. 与结构赋值默认值结合使用

1function foo({x, y = 5}) { 2 console.log(x, y); 3} 4foo({}) // undefined 5 5foo({x: 1}) // 1 5 6foo({x: 1, y: 2}) // 1 2 7foo() // TypeError: Cannot read property 'x' of undefined 8 9// 提供函数默认值 10function foo({x, y = 5} = {}) { 11 console.log(x, y); 12} 13foo() // undefined 5

3. 参数默认值的位置

1// 例一 2function f(x = 1, y) { 3 return [x, y]; 4} 5 6f() // [1, undefined] 7f(2) // [2, undefined]) 8f(, 1) // 报错 9f(undefined, 1) // [1, 1] 10 11// 例二 12function f(x, y = 5, z) { 13 return [x, y, z]; 14} 15 16f() // [undefined, 5, undefined] 17f(1) // [1, 5, undefined] 18f(1, ,2) // 报错 19f(1, undefined, 2) // [1, 5, 2]

如果传入 undefined ,将触发该参数等于默认值, null 则没有这个效果

1function foo(x = 5, y = 6) { 2 console.log(x, y); 3} 4 5foo(undefined, null) 6// 5 null

4. 函数的 length 属性 是指没有指定默认值的参数个数

5. name 属性

6. 箭头函数

7. 双冒号运算符

点赞
收藏

评论区

加载中...

相关推荐

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

MySQL ROUND函数:四舍五入

MySQL(https://www.oschina.net/action/GoToLink?urlhttp%3A%2F%2Fc.biancheng.net%2Fmysql%2F) ROUND(x)函数返回最接近于参数x的整数;ROUND(x,y)函数对参数x进行四舍五入的操作,返回值保留小数点后面指定的y位。【实例1】使用ROUN

ES6 参数默认值引起的中间作用域

ES6参数默认值的问题,其实之前在另一篇文章中已经有涉及,之所以再谈起这个问题,是在阅读《ES6标准入门》时产生的一个疑惑。阮老师的代码是:varx1;functionfoo(x,yfunction(){x2;}){varx3;y();console.log(x);}foo();

Javascript 变量 var与不var的区别

1.在函数作用域内加var定义的变量是局部变量,不加var定义的就成了全局变量。使用var定义var a  'hello World';function bb(){    var a  'hello Bill';    console.log(a);   }bb()   // 'hello Bill'conso

ES6中Generator理解

1\.生成器函数声明  function\ name(args){};2\.yield使用function hello(){    console.log('before hello');  //可看到hello()并不会立刻执行函数, 到第一次next调用时才会    var name 

12、ES6形参默认值

当定义函数的时候,可以给参数设置默认值。调用的时候不传递参数值,就使用默认值。例子1:普通函数,不传递参数值。默认全是undefined。functionadd(a,b,c){console.log(a,b,c);}add();//不传递参数是,默认参数值全是undef