问题:
I noticed that I had a type in one of my forEach statements but I still got the same result.
foo = ["bobby", "tommy", "brendan"]
foo.forEach((f => {
console.log(...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
I noticed that I had a type in one of my forEach statements but I still got the same result.
foo = ["bobby", "tommy", "brendan"]
foo.forEach((f => {
console.log(f)
}))
vs.
foo.forEach((f) => {
console.log(f)
})
I'm curious as to why the result would be the same on the first one, which I made the typo on.
回答1:
An arrow function with one argument can be written in two ways:
f => {
console.log(f)
}
And
(f) => {
console.log(f)
}
So the braces around the argument part are optional if there is only one argument.
And placing braces around a complete expression does not change anything for that expression, this:
f => {
console.log(f)
}
and this
(f => {
console.log(f)
})
or even this
((f => {
console.log(f)
}))
is identical.
Your first code block can be formatted as this for a better understanding:
foo.forEach(
// first argument of forEach
(f => {
console.log(f)
})
// end of argument list of forEach
)
So there are no misplaced braces, you just removed the optional ones around the f
and place optional once around the complete expression.
回答2:
foo.forEach((f => {
console.log(f)
}))
forEach
accepts two paramters(first is method/function and second is optional which value to use as this
object when executing callback), wrapping it around with ()
is not required. Although with arrow functions, if you have a single parameter you don't need to explicity wrap it with ()
, but you need to wrap you arguments if your method has multiple arguments.
You can check this out for further reading on arrow functions and this for forEach
in js