Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
435 views
in Technique[技术] by (71.8m points)

美团前端二面,读代码题求解

var a = 0;
if (true) {
    a = 1;
    function a() {}
    a = 21;
    console.log(a);
}
console.log(a);

求两次 console 出来的值。

答案是21 1。

本菜鸡想了很久也没想明白第二个为啥是1。。

求大佬解惑 ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

21 1 的输出结果不完全正确,在不同的浏览器下结果不同
在safari下结果为21 21
在chrome下结果为21 1

同时ECMAScript规范中说函数声明可以嵌套在条件语句块内,但是其运行的结果依赖于JS解析器的实现,其结果具有不确定性,不推荐在生产环境下使用

Functions can be conditionally declared, that is, a function statement can be nested within an if statement, however the results are inconsistent across implementations and therefore this pattern should not be used in production code. For conditional function creation, use function expressions instead.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...