_log = console.log //参数默认值 function log(x,y = 'world'){ _log(`${x} ${y}`); } log('hello') //hello world log('hello', 'china') //hello china function Point(x = 0, y = 0){ this.x = x; this.y = y; } _log(new Point()); function add(x = 1){ let x = 2; //报错 const x = 3; //报错 } //与解构解析配合 function foo({x, y=5}){ _log(x,y) } foo({}); //undefined , 5 foo({x:1}); //1 5 foo({x:1,y:10}); // 1 10 //foo() //报错 function fetch(url , {body='',method='GET',headers={} }){ console.log(method); } fetch('http://qq.com',{}); //GET //fetch('http://qq.com'); //报错 function fetch(url , {body='',method='GET',headers={}} = {}){ console.log(method) } fetch('http:qq.com'); function m1({x=0,y=0}={}){ console.log(x,y) } function m2({x,y} = {x:0,y:0}){ console.log(x,y); } m1(); //[00] m2(); //[0,0] m1({}); //[0,0] m2({}); //[undefined,undefined] //函数参数默认值,尽量放在尾部 function foo2(x, y=2){} console.log(foo2.length) //函数的length属性返回没有默认值参数的和 //作用域 var x = 1 function f(y=x){ console.log(y); } f(2);//2 /*function f2(y=x2){ let x2 = 2; console.log(y); //报错 } f2(); */ let foo = 'outer' function bar(func = x=> foo){ let foo = 'inner'; console.log(func()); } bar() //rest arguments function add(...values){ var sum = 0; for(let val of values){ sum += val; } return sum; } add(1,2,3,4,5)
rest 参数
function sum(...values){ let sum = 0; for(var i = 0; i < values.length; i++){ sum += values[i]; } return sum }
排序
const sortNumbers = (...numbers)=>numbers.sort()
扩展运算符
console.log(...[1,2,3] + 6) //1 , 2 , 3 6
function push(array, ...items){
array.push(...items)
}
var arr = [1,2,3]
push(arr, 4,5,6);
console.log(arr); //[1,2,3,4,5,6]
//代替es6 function f(x,y,z){} var args = [0,1,2]; f.apply(null ,args); //es5 f(...arg);//es6
var arr1 = [0,1,2] var arr2 = [3,4,5] Array.prototype.push.apply(arr1, arr2) //es5 arr.push(...arr2)//es6
//数组的合并 var arr1 = ['a', 'b']; var arr2 = ['c']; var arr3 = ['d', 'e']; arr.concat(arr2,arr3); //es5 [...arr1,...arr2,...arr3] //es6
let list = [1,2,3,4,5,6]; //let a = list[0], // rest = list.slice(1); //es5 //es6 [a, ...rest] = list;
const [first, ...rest] = ['foo']
//first 'foo'
//rest []
var go = function*(){ yield 1; yield 2; yield 3; } [...go()]
function foo(){} foo.bind({}).name; //"bound foo" (function(){}).bind({}).name //"bound "