ES6 入门第三章
函数参数默认值
- 形参初始值 具有默认值的参数,一般位置要靠后(潜规则)
//1.形参初始值 具有默认值的参数,一般位置要靠后(潜规则)
function add(a,b,c=10){
return a + b +c;
}
let result = add(1,2);
console.log(result);
如果实参只有两个,但形参有三个,则效果为:
function add(a,b,c){
return a + b +c;
}
let result = add(1,2);
console.log(result);
2. 与解构赋值结合
//2.与解构赋值结合
function connect({host="127.0.0.1",username,password,port}){
console.log(host);
console.log(username);
console.log(password);
console.log(port);
}
connect({
host:'localhost',
username:'root',
password:'root',
port:3306
})
rest参数
ES6 引入 rest 参数,用于获取函数的实参,用来代替 arguments
ES5 获取实参的方式
//ES5 获取实参的方式
function date(){
console.log(arguments);
}
date('西游记','红楼梦','水浒传','三国演义');
rest 参数
//rest 参数
function date(...args){
console.log(args);//filter some every map
}
date('小红','小橙','小黄');
rest 参数必须要放到参数最后
//rest 参数必须要放到参数最后
function fn(a,b,...args){
console.log(a);
console.log(b);
console.log(args);
}
fn(1,2,3,4,5,6);
如果 rest 参数不放到最后,效果如下:
function fn(a,...args,b){
console.log(a);
console.log(b);
console.log(args);
}
fn(1,2,3,4,5,6);
扩展运算符
[…] 扩展运算符能将[数组]转换为逗号分隔的[参数序列]
//声明一个数组 ...
const name = ['西游记','红楼梦','水浒传','三国演义'];
//=>'西游记','红楼梦','水浒传','三国演义'
//声明一个函数
function book(){
console.log(arguments);
}
book(name);
//声明一个数组 ...
const name = ['西游记','红楼梦','水浒传','三国演义'];
//=>'西游记','红楼梦','水浒传','三国演义'
//声明一个函数
function book(){
console.log(arguments);
}
book(...name);//book('西游记','红楼梦','水浒传','三国演义')
扩展运算符应用
- 数组的合并
//1.数组的合并
const book = ['西游记','红楼梦'];
const book2 = ['人性的弱点','狼道'];
const bookTotal = book.concat(book2);
console.log(bookTotal);
const book = ['西游记','红楼梦'];
const book2 = ['人性的弱点','狼道'];
//const bookTotal = book.concat(book2);
const bookTotal = [...book,...book2];
console.log(bookTotal);
- 数组的克隆
//2.数组的克隆
const sanzhihua = ['E','G','M'];
const sanyecao = [...sanzhihua];
console.log(sanyecao);
- 将伪数组转为真正的数组
//3.将伪数组转为真正的数组
const divs = document.querySelectorAll('div');
//console.log(divs);
const divArr = [...divs];
console.log(divArr);