yaogengzhu / Learning-notes

基础回顾、笔记
1 stars 0 forks source link

【入门1-2】认识es6中的函数 #2

Open yaogengzhu opened 4 years ago

yaogengzhu commented 4 years ago

函数

  1. 默认参数 (a.必填项不填报错 b. 有些参数不传递参数的话有默认值)
    
    function ajax(url = new Error('url 不能为空'), method = 'GET', dataType = 'json') {
    console.log(url)
    console.log(method)
    console.log(dataType)
// if (typeof url === 'undefined') thorw Error('url 不能为空')

}


>  解析成es5
```js
"use strict";
function ajax() {
  var url = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Error('url 不能为空');
  var method = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'GET';
  var dataType = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'json';
  console.log(url);
  console.log(method);
  console.log(dataType); 
  // if (typeof url === 'undefined') thorw Error('url 不能为空')
}
ajax('/user')
  1. 展开操作符

// 实现reduce方法 Array.prototype.reduce1 = function(reducer, initialval) { for (let i = 0; i < this.length; i++ ) { // 递归 initialval = reducer(initialval, this[i]) } return initialval }

const result2 = [1,2, 4].reduce1(function(val, item) { return val + item }, 0)

console.log(result2)

let arr4 = [1, 2, 3] let arr5 = [4, 5, 6] let arr6 = [].concat(arr4).concat(arr5) // 展开运算符,相当于把数组的每个元素依次取出放出 let arr7 = [...arr4, ...arr5] console.log(arr6) console.log(arr7)

// 拿出最大值 let max = Math.max(...arr7) console.log(max)

let obj1 = { name: 1 } let obj2 = { age: 22 } let obj3 = {}


> 对象复制
- 1. 循环赋值
```js
for(let key in obj1) {
    obj3[key] = obj1[key]
}
for(let key in obj2) {
    obj3[key] = obj2[key]
}
console.log(obj3)

// 实现简单的深拷贝 function cloneDeep(obj) { let newObj = {} for(let key in obj) { if (typeof key === 'object') { newObj[key] = cloneDeep(obj[key]) } else { newObj[key] = obj[key] } }

return newObj

}


> 箭头函数

```js
let sum21 = function(a, b) {
    return a + b
}

// 简化1
let sum31 = (a, b) =>  {
    return a + b
}

// 简化2 
let sum22 = (a, b) => a + b

// 简化3 如果只有一个参数
let test = b => b

let obj = {
    name1: 'zhuyaogeng',
    getName() {
        setTimeout(() => {
            console.log(this.name1, 'name1')
        }, 100)
    }
}
obj.getName()

结果

/user
GET
json
$19.25
7
[ 1, 2, 3, 4, 5, 6 ]
[ 1, 2, 3, 4, 5, 6 ]
6
{}
{ name: 1, age: 22 }
huangshi
wuhan