【问题标题】:Why wrong spelling in str.length doesn't show an error in JS为什么 str.length 中的拼写错误不会在 JS 中显示错误
【发布时间】:2018-06-29 06:10:52
【问题描述】:
我是初学者 javascript 开发人员,我编写了以下代码:
var foo = "sunny";
var longitudInt = foo.length;
console.log("The length of " + foo + " is " + longitudInt);
但是我写foo.length的时候,拼写错误,写了foo.lenght,但是在控制台没有显示错误,为什么?
It doesn't show an error
【问题讨论】:
标签:
javascript
console
string-length
misspelling
【解决方案1】:
foo.lenght 不会引发错误,但会返回 undefined。原因是foo 是一个String 类型变量,当它尝试调用属性lenght(这是无效的)时,它在其原型中没有得到它。因此,它返回 undefined 而不是错误。
var foo = 'str';
console.log(foo.lenght);
但是,如果您尝试访问foo.lenght 中的其他属性,例如foo.lenght.len,那么这将给您错误,因为此时foo.lenght 是undefined,它会尝试读取undefined 的属性输入。
var foo = 'str';
console.log(foo.lenght.len);
【解决方案2】:
“something”.lenght(或其他任何东西,“something”.foobar)的值将是“undefined”(大致相当于 null)。
它不会像其他一些语言那样抛出异常