简体   繁体   English

我该如何调试JavaScript错误?

[英]How do I debug javascript errors like this?

I'm new to javascript and was trying to figure out why the following code was not working: 我是javascript的新手,并试图弄清楚以下代码为何不起作用:

let ws = new WebSocket("ws://echo.websocket.org/");
ws.onmessage = msg => console.log(msg);
let queue = [];
ws.onopen = () => {
    queue.forEach(msg => ws.send(msg));
};

const send = () => {
    if(ws.readyState === ws.OPEN){
        ws.send(msg);
    }
    else{
      queue.push(msg);
    }
};

send("foo");
send("bar");

Then I realized that I needed: let send = (msg) => { . 然后我意识到自己需要: let send = (msg) => {

Before finding the problem, I had used lint and dev tools but I cdidn't see any warnings. 在发现问题之前,我曾使用过lint和dev工具,但看不到任何警告。 What should I be doing to find there kinds of problems? 我应该怎么做才能发现那里的问题?

http://www.es6fiddle.net/iu3qwem6/ http://www.es6fiddle.net/iu3qwem6/

eslint. eslint。 There's even a specific rule for this one: http://eslint.org/docs/rules/no-undef 甚至还有一个特定的规则: http : //eslint.org/docs/rules/no-undef

You should probably get a ReferenceError, because your let/const implies strict syntax, though if you missed that I'm guessing your engine wasn't picking up on strict mode for whatever reason. 您可能应该得到一个ReferenceError,因为let / const表示严格的语法,尽管如果您错过了我以为您的引擎由于某种原因而没有采用严格模式的情况。 It's a better error to find with static analysis anyway, because it will pick up the error even if the function is never called. 无论如何,使用静态分析来查找是一个更好的错误,因为即使从未调用该函数,它也会拾取错误。

I recommend you give TypeScript a try. 我建议您尝试一下TypeScript。 Have a look at your example at TypeScript playground . TypeScript操场上查看您的示例。

It will immediatelly tell you: Cannot find name msg inside your send function. 它会立即告诉您:在send函数中Cannot find name msg

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM