JavaScript, 箭头函数
JavaScript, Arrow functions
我很难理解这个例子中的箭头函数:
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;
const printArray = (array) => {
array.forEach(element => {
console.log(element);
});
};
这应该是正确的语法:)
就减少到
const printArray = array => {
array.forEach(console.log);
};
我很难理解这个例子中的箭头函数:
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;
const printArray = (array) => {
array.forEach(element => {
console.log(element);
});
};
这应该是正确的语法:)
就减少到
const printArray = array => {
array.forEach(console.log);
};