javascript-未捕获的SyntaxError:标识符*已被声明 [英] javascript- Uncaught SyntaxError: Identifier * has already been declared

查看:140
本文介绍了javascript-未捕获的SyntaxError:标识符*已被声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

console.log(a) //output:ƒ a(){}
var a = 1;
function a(){};
var a = 10;
console.log(a) //output:10

===================

====================

var a = 1;
if(true){
  function a(){};
  var a = 10;
}
console.log(a) // this code throws Uncaught SyntaxError: Identifier 'a' has already been declared

以上两个代码段都是相同的,除了if块.当if块在javascript中允许在同一范围内使用del两次对同一变量进行delcare时,为什么会抛出错误

both above code snippets are same except the if block.why does the latter throws error when its permissible in javascript to delcare same variable twice in the same scope with var as below

 function a(){};
 var a = 10; //no error

在上述代码中从`var a = 10中删除var后,对于稍微不同的情况,

Also for a slightly different scenario after removing var from `var a = 10 in the above code ,then it works fine but output is surprising

 var a = 1;
 if(true) {
   function a(){};
   a = 10;
 }
 console.log(a) //output:ƒ a(){}

我很惊讶地看到此输出,因为我期望10 ..因为在if块内声明的两个变量引用了上面声明的同一变量,因为javascript var不尊重块范围而是功能范围...所以为什么不输出以上应该是10?当下面的代码将函数定义替换为函数表达式时,下面的代码输出预期的10.

I am surprised to see this output as I am expecting 10 ..because two variables declared inside the if block refer to the same variable declared above as javascript var doesnt respect block scope but functional scope...so why not the output for above should be 10? where as the below code outputs 10 as i expected when replaced the function definition with function expression.

  var a = 1;
  if(true) {
    var a = function(){ console.log() }
    a = 10;
  }
  console.log(a) //output:10

推荐答案

这令人惊讶,因为javascript var 不遵守块范围,而是功能范围...

This is surprising as javascript var doesn't respect block scope but functional scope...

可以,但是您没有在块作用域中使用 var 来声明 a .您使用了一个函数声明, 确实遵守了块作用域(否则将是完全无效的代码,如在ES5严格模式下一样.

Sure, but you didn't use var for the declaration of a in the block scope. You used a function declaration, which does respect block scopes (otherwise it would be completely invalid code, as in ES5 strict mode).

在JavaScript中,可以使用 var 如下所示在同一范围内两次声明相同的变量

It's permissible in javascript to declare same variable twice in the same scope with var as below

此处同样适用.块中的 function 声明使用ES6声明语义(如 let const ),不允许重新声明.

Same applies here. The function declaration in the block uses ES6 declaration semantics (like let or const), which does not allow redeclarations.

这篇关于javascript-未捕获的SyntaxError:标识符*已被声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆