基本用法
function log(x,y = 'World') {
console.log(x,y);
}
log('Hello') // Hello World
log('Hello','China') Hello China
log('Hello','') Hello
function foo(x = 5) {
let x = 1; error
const x = 2; error
}
与解构赋值默认值结合使用
function foo({x,y = 5}) {
console.log(x,y);
}
foo({}) undefined,5
foo({x: 1}) 1,5
foo({x: 1,y: 2}) TypeError: Cannot read property 'x' of undefined
参数默认值的位置
例一
function f(x = 1,y) {
return [x,y];
}
f() [1,undefined]
f(2) [2,undefined])
f(,1) 报错
f(undefined,1]
例二
function f(x,z) {
[undefined,5,undefined]
f(1) 报错
f(1,undefined,2]
function foo(x = 5,y = 6null)
5 null
函数的length属性
(function (a) {}).length 1
(function (a = 5) {}).length 0
(function (a,b,c = 5) {}).length 2
(function(...args) {}).length 0
(function (a = 0,c) {}).length 1
作用域
var x = 1;
x) {
console.log(y);
}
f(2) 2
let x = 1function f(y = x) {
let x = 2;
console.log(y);
}
f() 1
function throwIfMissing() {
throw new Error('Missing parameter');
}
function foo(mustBeProvided = throwIfMissing()) {
mustBeProvided;
}
foo()
Error: Missing parameter
function foo(optional = undefined) { ··· }
add(...values) {
let sum = 0;
for (var val of values) {
sum += val;
}
sum;
}
add(2,3) 10
arguments变量的写法
sortNumbers() {
Array.prototype.slice.call(arguments).sort();
}
rest参数的写法
const sortNumbers = (...numbers) => numbers.sort();
(function(a) {}).length function(...a) {}).length function(a,...b) {}).length 1
含义
console.log(...[1,2,3])
1 2 3
console.log(1,...[2,3,4],5 1 2 3 4 5
[...document.querySelectorAll('div')]
[<div>,<div>,<div>]
替代数组的apply方法
ES5的写法
f(x,1)"> ...
}
var args = [0,1,2];
f.apply( ES6的写法
];
f(...args);
扩展运算符的应用
ES5
[1,1)">].concat(more)
ES6
[1,...more]
ES5
a = list[0],rest = list.slice(1 ES6
[a,...rest] = list
var dateFields = readDateFields(database);
var d = new Date(...dateFields);
[...'hello']
[ "h","e","l","o" ]
'x\uD83D\uDE80y'.length 4
[...'x\uD83D\uDE80y'].length 3
var nodeList = document.querySelectorAll('div');
var array = [...nodeList];
var func1 = () {};
ES5
func1.name ""
ES6
func1.name "func1"
foo() {};
foo.bind({}).name "bound foo"
(function(){}).bind({}).name "bound "