4.参数默认值&&不确定参数&&箭头函数

2020-10-13  本文已影响0人  yaoyao妖妖

参数默认值

function f (x, y, z) {
  if (y === undefined) {
    y = 7
  }
  if (z === undefined) {
    z = 42
  }
  return x + y + z
}

console.log(f(1, 8, 43))

function f (x, y = 7, z = x + y) {
  console.log(f.length)  // 代表函数参数 arguments,ES6中禁止使用 arguments,可以使用f.length 获取没有默认值的参数
  return x * 10 + z
}
console.log(f(1, undefined, 3, 4))

// 不确定参数的问题 es5 arguments es6
ES5

function sum () {
  let num = 0
  Array.prototype.forEach.call(arguments, function (item) {
    num += item * 1
  })
  // Array.from(arguments).forEach(function (item) {
  //   num += item * 1
  // })
  return num
}

ES6

function sum (base, ...nums) {
  // Rest parameter
  let num = 0
  nums.forEach(function (item) {
    num += item * 1
  })
  return base * 2 + num
}
console.log(sum(1, 2, 3))

function sum (x = 1, y = 2, z = 3) {
  return x + y + z
}
let data = [4, 5, 9]
// console.log(sum(data[0], data[1], data[2]))
// console.log(sum.apply(this, data)) // ES5 自动将数组对应到参数上去
// spread
console.log(sum(...data)) // ES6 

ES6 中的箭头函数 ()=>{}

function hello () {}
let hello = function () {}
let sum = (x, y, z) => {
  return {
    x: x,
    y: y,
    z: z
  }
}
console.log(sum(1, 2, 4))

let test = {
  name: 'test',
  say: () => {
    console.log(this.name, this)
  }
}
test.say()

学习视频记录

上一篇 下一篇

猜你喜欢

热点阅读