首页 > 解决方案 > JavaScript,箭头函数

问题描述

我正在努力理解这个例子中的箭头函数:

const printArray = function (array) {
  array.forEach(function (element) {
    console.log(element);
  });
};

我一直在尝试:

const printArray = array => {
  array.forEach = element => {
    console.log(element)
  }
}

然而,这行不通。有人可以在上面的例子中澄清我吗?

标签: javascriptarrow-functions

解决方案


这是正确的方法

const printArray = array => {
  array.forEach(element => {
    console.log(element);
  });
};

function(a) {}被替换 被a => {}
function(b) {return x}替换b => x
function(c,d) {}被替换(c,d) => {}

forEach()是函数调用,不是函数定义。只有定义是用数组函数表达式编写的。

有关更多信息,请参见此处: https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

将传统函数表达式转换为箭头函数表达式的步骤

function (a) {
  return a + 100;
}

// 'Replace' `function` with `=>`

(a) => {
  return a + 100;
}

// If function body consists of only a return statement

(a) => a + 100;

// If function only has one parameter

a => a + 100;


推荐阅读