JavaScript中forEach方法如何与三元运算符及if语句配合使用?
Hey there! Let's break down exactly why those frustrating SyntaxErrors are popping up and get your code running smoothly.
What's Wrong with Line 3?
Your third line of code looks like this:
let checkArr = (arr) => arr.forEach(el => if (typeof el !== 'string') { console.log(`Type error: ${el} should be a string!`)})
The core issue here is how arrow functions work with concise syntax (no curly braces {}). When you omit curly braces for an arrow function, its body can only contain an expression—not a full statement like if. The if keyword kicks off a statement, which violates this rule and triggers the Unexpected token if error.
To fix this, wrap the inner arrow function's body in curly braces to use a block statement:
let checkArr = (arr) => arr.forEach(el => { if (typeof el !== 'string') { console.log(`Type error: ${el} should be a string!`) } })
What's Wrong with Line 4?
Your fourth line has two small but critical syntax issues:
let checkArr = ((arr) => { arr.forEach(el => typeof el !== 'string' ? console.log(`Type error: ${el} should be a string!`) : null; )})
- Extra semicolon: Inside the
forEacharrow function, you added a semicolon afternull. Since this is a concise arrow function using an expression (the ternary operator), that semicolon doesn't belong here—it's what causes themissing ) after argument listerror. - Redundant outer parentheses: The wrapping
((arr) => { ... })is unnecessary; you can just use(arr) => { ... }directly.
Here's the cleaned-up version:
let checkArr = (arr) => { arr.forEach(el => typeof el !== 'string' ? console.log(`Type error: ${el} should be a string!`) : null ) }
And since the null case does nothing, you can simplify it even further by ditching the ternary entirely (this is more readable anyway):
let checkArr = (arr) => { arr.forEach(el => { if (typeof el !== 'string') { console.log(`Type error: ${el} should be a string!`) } }) }
Quick Best Practice Note
You're redeclaring checkArr three times with let—while this isn't a syntax error, it's messy. You only need to declare checkArr once, then assign your corrected function to it.
Full Working Code
Putting it all together, here's your code without any syntax errors:
let arr = ['Custy Stomer', 'C. Oostomar', 'C.U.S. Tomer', 3432434, 'Custo Mer', 'Custopher Ustomer', 3432435, 'Kasti Yastimeur']; let checkArr = (arr) => { arr.forEach(el => { if (typeof el !== 'string') { console.log(`Type error: ${el} should be a string!`) } }) } checkArr(arr);
This will correctly log the type errors for the numeric elements in your array.
内容的提问来源于stack exchange,提问作者v01d

