javascript - JavaScript,箭头函数
问题描述
我正在努力理解这个例子中的箭头函数:
const printArray = function (array) {
array.forEach(function (element) {
console.log(element);
});
};
我一直在尝试:
const printArray = array => {
array.forEach = element => {
console.log(element)
}
}
然而,这行不通。有人可以在上面的例子中澄清我吗?
解决方案
这是正确的方法
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;
推荐阅读
- json - JSON 的 JOLT 转换最初来自 Protobuf 格式
- c++ - PyTorch C++ 前端向前返回多个张量
- javascript - 使用带有 fetch json 的 DELETE 方法找不到错误 404
- python - 我的代码在 Jupyter Notebook 中工作,但不能作为 Python 脚本
- python - 正则表达式来标记句子python
- c - 在c中的文件中写入直到n的偶数整数,putw()函数错误
- flutter - 是否可以以编程方式控制 Flutter 中的选项卡(隐藏/可见)
- c - 如何在 C 编程中使用 Strtol 将包含逗号的整数与文本文件分开?
- r - 如何保存从ggplot中保存的颜色?
- python - 如何退出此程序中的循环