

#yyds干货盘点#javascript的奇葩问题
source link: https://blog.51cto.com/u_11365839/5659978
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

作为前端开发工程师,JavaScript 是我们的主要开发语言,它本身语法比较简单,并且生态系统也非常完善,在社区的影响力越来越大。
在我们使用过程中,经常会遇到各种奇怪的问题,让我们经常摸不着头脑。
奇怪的 try..catch
下面代码执行后将返回什么?2
还是 3
?
try {
return 2;
} finally {
return 3;
}
})();
答案是 3
,这是为什么呢?这是因为在 try...catch...finally
语句中,无论是否抛出异常 finally
子句都会执行。此外,如果抛出异常,即使没有 catch
子句处理异常,finally
子句中的语句也会执行。
[]
和 null
都是对象
下面 3 行代码返回结果是什么?
typeof null;
null instanceof Object;
返回结果是这样的:
typeof null; // -> 'object'
null instanceof Object; // false
typeof
操作符返回一个字符串,且必须符合 Table 37: typeof 操作符 返回值。对于没有实现 [[Call]]
的 null
、普通对象、标准特异对象和非标准特异对象,它返回字符串 'object'
。
// expected output: "number"
console.log(typeof '前端自习课');
// expected output: "string"
console.log(typeof true);
// expected output: "boolean"
console.log(typeof undeclaredVariable);
// expected output: "undefined"
但是,你可以使用 toString
方法检查对象的类型。
// -> '[object Array]'
Object.prototype.toString.call(new Date());
// -> '[object Date]'
Object.prototype.toString.call(null);
// -> '[object Null]'
箭头函数返回 undefined
函数 f2
执行后为什么返回了 undefined
?
f1(); // -> '前端自习课'
let f2 = () => {};
f2(); // -> undefined
我们第一眼感觉应该是返回 {}
,可是却返回了 undefined
,这本质原因是因为箭头函数返回的 {}
是箭头函数语法的一部分,我们写一个测试用例就能看出来:
return '前端自习课'
};
f2(); // -> '前端自习课'
因此上面 f2
函数返回的是 undefined
,当然,如果需要返回一个 {}
对象也是可以的,只需要使用括号将返回值包裹起来:
f2(); // -> {}
还能使用反引号执行函数?
调用函数除了下面的方式,还有其他方式吗?
return args;
}
f(1, 2, 3); // -> [ 1, 2, 3 ]
当然还有啦,我们可以使用反引号调用:
/*
[
["Hello string ", ", Hello boolean ", ", Hello array ", ""],
"前端自习课",
false,
[1, 2, 3]
]
*/
这个看着很神奇的样子,但是实际上用的是 模版字符串。这是一种高级形式的模版字符串,是带标签的模版字符串。
上面示例代码中:f
函数是模版字面量的标签,标签可以用函数解析模板字符串。标签函数的第一个参数包含一个字符串值的数组。其余的参数与表达式相关。
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK