片段 - 标识符已经被声明 [英] Snippets - Identifier has already been declared

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

问题描述

我在Chrome代码片段中写道:

  let commitPromotionData =(product)=>新的Promise((resolve,reject)=> {
//对服务器做些什么
var statusCode = 200;

statusCode == 200?resolve(product):拒绝();
});

当我第二次尝试运行它时,它说变量已经被声明并抛出错误是:
$ b


未捕获的SyntaxError:标识符'commitPromotionData'已经将
声明为
at:1:1


当然,这是是控制台的默认行为,但在这里似乎没有太大意义。



这是打算吗?有没有办法解决这个问题?

解决方案

我相信你遇到了一个事实,即 let 语句只能用于在任何给定范围内创建一个变量。在你的例子中,即使你使用的是Chrome代码片段,如果你在 let 语句之后输出 window.commitPromotionData 你会看到它在那里。这就是你的 let 语句赋予变量的范围。重新运行相同的片段本质上会尝试在窗口内创建相同的变量,并导致语法错误,如文档所述这里



您有两种解决方法:


  1. 很明显,第一种方法是将任何顶部或者创建一个新的块作用域 let 语句到 var

  2. 用于包装代码。这可以通过将代码包装在IIFE (function(){... code ...})()


I wrote this in a Chrome snippet:

let commitPromotionData = (product) => new Promise((resolve, reject) => {
    //Do something with the server
    var statusCode = 200;

    statusCode == 200 ? resolve(product) : reject();
});

And when I try to run it 2nd time, it says the variable has already been declared and throws an error at first line.

The error is:

Uncaught SyntaxError: Identifier 'commitPromotionData' has already been declared at :1:1

And of course, this is would be the default behavior for the Console but it doesn't seem to make much sense here..

Is this intended? Is there any way around this?

解决方案

I believe you're running into the fact that a let statement can only be used to create a variable once in any given scope. In your example, even though you're using Chrome snippets, if you output window.commitPromotionData right after the let statement you'll see that it is there. That's the scope your let statement is assigning the variable to. Re-running the same snippet essentially tries to create the same variable within window and results in syntax error as documented here.

You have two workarounds:

  1. Obviously the first is to convert any top level let statements to var's
  2. Or create a new block scope for wrapping the code. This can be done for instance by wrapping the code in an IIFE (function(){ ... code ... })()

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

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