在 JavaScript 中使用带字符串的开关

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4253865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:36:16  来源:igfitidea点击:

Using a switch with strings in JavaScript

javascriptstringtextareaswitch-statement

提问by MF Ramen

My switchstatement is not working properly when analysing a string variable.

switch分析字符串变量时,我的语句无法正常工作。

The output and input are both <textarea>'s.

输出和输入都是<textarea>

HTML

HTML

<form name="interface">
  <textarea name="output" rows="20" cols="100"></textarea><br>
  <textarea name="input" rows="1" cols="100" onKeyDown="thinkInput(event);"></textarea>
</form>

JavaScript

JavaScript

function thinkInput(e)
{
    if (e.keyCode == 13)
    {
        sInput = document.interface.input.value;
        document.interface.output.value += sInput;
        aInput = sInput.split(" ");

        switch (aInput[0])
        {
            case "say":
                textOut("You say \""+sInput.substring(aInput[0].length + 1)+"\"");
                break;
            case "move":
                move(aInput[1]);
                break;
            default:
                thinkFail();
                break;
        }
        document.interface.input.value = null;
        alert(aInput[0]);
    }
}

I can see in my alert()at the end that the case is either "say" or "move".

我可以在alert()最后看到案例是“说”或“动”。

The first time I try to "say mudkipz" or "move around", everything works as I want it, but after that everything I type, thinkFail()fires.

我第一次尝试“说 mudkipz”或“四处走动”时,一切都按我想要的方式工作,但在那之后,我键入的所有内容都会thinkFail()触发。

回答by Matej Svajger

Your code isn't executing due to a new line that appears above the command prompt and the split array doesn't contain the reference first word on [0] value. Don't know why, even though you're clearing the value of input.

由于出现在命令提示符上方的新行,您的代码未执行,并且拆分数组不包含 [0] 值上的引用第一个单词。不知道为什么,即使您正在清除输入的值。

Since you'll be needing only one line on this input, I suggest using <input type="text" onKeyDown="thinkInput(event);"/>to avoid getting new lines on enter.

由于您在此输入中只需要一行,我建议使用<input type="text" onKeyDown="thinkInput(event);"/>以避免在输入时出现新行。

JavaScript

JavaScript

this.thinkInput = function (e)
{   
    ...

    if (e.keyCode == 13)
    {   
        /* Prevent submitting form on Enter */ 
        e.preventDefault();

        var command, commands;

        command = cmd.value;
        commands = command.split(' ');
        /* Clear input field */
        cmd.value = '';

        /* commands[0] will always have reference
           to the first word in textfield */
        switch (commands[0])
        {
            ...
        }
    }
}

Here is a little fiddle I threw together from your code: http://jsfiddle.net/npx86/1/

这是我从你的代码中拼凑出来的一个小小提琴:http: //jsfiddle.net/npx86/1/

Hope this helps!

希望这可以帮助!

回答by rbhro

One issue is that you are not using the varstatement to define your variables. This means they become "implicit globals", and are kept through your different calls.

一个问题是您没有使用该var语句来定义您的变量。这意味着它们成为“隐式全局变量”,并通过您的不同调用保持。

var sInput = document.interface.input.value;
var aInput = sInput.split(" ");
document.interface.output.value += sInput;

To further diagnose the problem, you can use the debugger tools in your browser to insert a breakpoint, and step through to monitor the value of sInputand to locate the problem.

要进一步诊断问题,您可以使用浏览器中的调试器工具插入断点,并逐步监控值sInput并定位问题。

回答by Ja?ck

This happens because afterresetting the inputbox value to empty, the pressed key (enter) gets added. This causes aInput[0]to start with a CR (which you wouldn't see in the alert()message.

发生这种情况是因为input框值重置为空后,按下的键 (enter) 被添加。这会导致aInput[0]以 CR 开头(您不会在alert()消息中看到。

You can easily fix this by trimming the left side of sInputbefore you split it:

您可以通过sInput在拆分之前修剪左侧来轻松解决此问题:

aInput = sInput.replace(/^\s+/,'').split(" ");

Alternatively, you can cancel the keydownevent by returning falseexplicitly from the function when <CR>is pressed and change the HTML to:

或者,您可以keydown通过false<CR>按下时从函数显式返回来取消事件,并将 HTML 更改为:

onkeydown="return thinkInput(event);"

回答by widged

Did you try any of these?

你有没有尝试过这些?

at the end

在末尾

document.interface.input.value = ""; 

It really should be an empty string, as null + "hello" > "nullhello"

它真的应该是一个空字符串,如 null + "hello" > "nullhello"

or at the start

或者一开始

document.interface.output.value = sInput; 

Does it actually serve a purpose to add the string if you reset the output value each time?

如果每次都重置输出值,它实际上是否有助于添加字符串?

回答by Android334

Maybe I'm missing something... when I'm looking/testing this code it runs every time the keydown event is triggered and because you are clearing the input field we are only working with single characters.

也许我遗漏了一些东西......当我查看/测试这段代码时,它会在每次触发 keydown 事件时运行,并且因为您正在清除输入字段,我们只使用单个字符。

If I were to type "say" then the code would execute with "s", then "a", then "y".

如果我输入“say”,那么代码将依次使用“s”、“a”和“y”执行。

If what you're wanting to do if scan the textarea for those words, I'd recommend pulling the value of document.interface.output.valueand comparing that value against your case.

如果您想在 textarea 中扫描这些单词,我建议您提取 的值document.interface.output.value并将该值与您的案例进行比较。

Hope this helps.

希望这可以帮助。

EDIT:Can you post your move method, textOut method and thinkFail method? From what I can tell if any exception is hit then that is when the case doesn't work. I created a jsfiddlewhere it works fine.

编辑:你能发布你的移动方法、textOut 方法和 thinkFail 方法吗?据我所知,如果遇到任何异常,那就是这种情况不起作用的时候。我创建了一个jsfiddle,它可以正常工作。

回答by user3281733

Put this line before the switch ....

将此行放在开关之前....

aInput = sInput.split(" ");
aInput[0] = aInput[0].replace(/\s/gi, "");

switch (aInput[0])
{

....

....

Or you can use for the text input, instead of textarea.

或者您可以用于文本输入,而不是 textarea。

回答by Mathias

I know it has been a while since this was asked but I have to provide an answer anyway.

我知道自从问这个问题已经有一段时间了,但无论如何我必须提供一个答案。

The reason your code is not working is that the input Textarea is not empty after the first try. The linebreak is still added to the textarea after the code is run and the next time you press enter it is the first char in the input.

您的代码不起作用的原因是第一次尝试后输入 Textarea 不为空。代码运行后,换行符仍会添加到文本区域,下次按回车键时,它是输入中的第一个字符。

If you either change the onKeyDown to onKeyUp or add a new eventHandler for onKeyUp to empty the input you should be fine.

如果您将 onKeyDown 更改为 onKeyUp 或为 onKeyUp 添加新的 eventHandler 以清空输入,则应该没问题。

<textarea name="input" rows="3" cols="100" onKeyUp="thinkInput(event);"></textarea>

http://jsfiddle.net/borglinm/ntj3t/1/

http://jsfiddle.net/borglinm/ntj3t/1/