Skip to content
On this page

函数

默认参数

可以给定义的函数接收的参数设置默认的值 在执行这个函数的时候,如果不指定函数的参数的值,就会使用参数的这些默认的值。

javascript
function ajax(url,method='GET',dataType="json"){
  console.log(url);
  console.log(method);
  console.log(dataType);
}
1
2
3
4
5

展开操作符

把。.. 放在数组前面可以把一个数组进行展开,可以把一个函数而不需要使用apply

javascript
//传入参数
let print = function(a,b,c){
    console.log(a,b,c);
}
print([1,2,3]);
print(...[1,2,3]);

// 可以替代apply
var m1 = Math.max.apply(null, [8, 9, 4, 1]);
var m2 = Math.max(...[8, 9, 4, 1]);

// 可以替代concat
var arr1 = [1, 3];
var arr2 = [3, 5];
var arr3 = arr1.concat(arr2);
var arr4 = [...arr1, ...arr2];
console.log(arr3,arr4);

//类数组的转数组
function max(a,b,c) {
    console.log(Math.max(...arguments));
}
max(1, 3, 4);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

剩余操作符

剩余操作符可以把其余参数的值放在一个叫做 b 的数组里

javascript
let rest = function(a,...rest){
    console.log(a,rest);
}
rest(1,2,3);
1
2
3
4

解构参数

javascript
let destruct = function({name,age}){
	console.log(name,age);
}
destruct({name:'wjh',age:10})
1
2
3
4

箭头函数

箭头函数简化了函数的定义方式

javascript
[1,2,3].forEach(val=>console.log(val));
1

箭头函数在一句返回时可以不写 return

javascript
[1,2,3].map(item=>item>2);
1

输入参数如果多于一个要用 () 包含,函数体如果有多条语句需要用{}包起来

箭头函数根本没有自己的 this,导致内部的 this 就是外层代码块的 this。 正是因为它没有 this,从而避免了 this 指向的问题。

javascript
var person = {
    name:'wjh',
    getName:function(){
-        setTimeout(function(){console.log(this);},1000); //在浏览器执行的话this指向window
+        setTimeout(() => console.log(this),1000);//在浏览器执行的话this指向person
    }
}
person.getName();
1
2
3
4
5
6
7
8
javascript
function fn() {
    console.log('real', this)  // {a: 100} ,该作用域下的 this 的真实的值
    var arr = [1, 2, 3]
    // 普通 JS
    arr.map(function (item) {
        console.log('js', this)  // window 。普通函数,这里打印出来的是全局变量,令人费解
        return item + 1
    })
    // 箭头函数
    arr.map(item => {
        console.log('es6', this)  // {a: 100} 。箭头函数,这里打印的就是父作用域的 this
        return item + 1
    })
}
fn.call({a: 100})

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
沪ICP备20006251号-1