函数返回零?拼写错误的x.lenght未触发报错的原因及解决方案问询
Awesome questions—let’s unpack each one clearly:
1. Why does the function return 0?
Let’s break this down with your code example (simplified for clarity):
function countBs(x) { let counter = 0; for (let i = 0; i < x.lenght; i++) { // Typo here: "lenght" instead of "length" if (x[i] === 'B') counter++; } return counter; }
Here’s what’s happening under the hood:
- If
xis a string (which it likely is, since you’re counting 'B's), strings have a built-inlengthproperty—but nolenghtproperty. - In JavaScript, accessing an object property that doesn’t exist won’t throw an error. Instead, it silently returns
undefined. - Next, the loop condition
i < undefinedruns. In JS, comparing a number toundefinedconvertsundefinedtoNaN(Not a Number). Any comparison involvingNaNreturnsfalse. - Since the condition is
falseright from the start (wheni = 0), the loop body never executes. Thecountervariable stays at 0, so the function returns 0.
2. Why didn’t JavaScript catch this error?
JavaScript is a dynamic, loosely typed language, and this behavior is intentional by design:
- Accessing a non-existent property isn’t a syntax error (those are things like missing brackets or invalid keywords) or a reference error (which happens when you use an undeclared variable).
- Instead, JS uses "silent failure" for missing properties—it returns
undefinedrather than crashing your program. This flexibility is useful in some cases, but it’s also a common source of bugs like yours. - The runtime doesn’t flag this because it can’t read your intent—it assumes you might have meant to check for a
lenghtproperty that could exist in some custom context.
3. How to catch these errors early?
Here are practical ways to avoid this kind of typo moving forward:
- Use TypeScript: It’s a statically typed superset of JavaScript that catches these errors at compile time. If you try to access
x.lenghton a string, TypeScript will immediately throw a warning like: Property 'lenght' does not exist on type 'string'. Did you mean 'length'? - Enable ESLint: Configure ESLint with rules that flag suspicious code. Plugins like
eslint-plugin-unicornor basic type-aware rules can detect when you’re accessing properties that don’t exist on standard built-in objects. Most editors (like VS Code) integrate ESLint to show warnings as you write code. - Leverage editor IntelliSense: Modern editors like VS Code have smart autocompletion for JavaScript/TypeScript. When you type
x., it will show a list of valid properties (includinglength). If you ignore autocomplete and typelenght, the editor will highlight it as an error (even in plain JS, if you enable type checking in settings). - Write unit tests: Create test cases for functions like
countBs—for example, test thatcountBs("BBB")returns 3. If your typo makes the function return 0 instead, the test will fail, and you’ll catch the bug before it reaches production.
内容的提问来源于stack exchange,提问作者Jahmul14
相关产品推荐
相关产品推荐

