【问题标题】:Javascript function not working with certain if/else statements for some reason由于某种原因,Javascript 函数不能与某些 if/else 语句一起使用
【发布时间】:2012-12-09 06:27:34
【问题描述】:

由于一些我无法弄清楚的奇怪原因,当我在其中包含这些 if/else 语句时,代码将无法工作,当它们不存在时它可以正常工作。我认为这与我附加到 if/else 语句的条件有关,因为当使用更简单的条件时,它似乎没问题。谁能告诉我我做错了什么?

    function wordSplit(){
        var sentence = document.getElementById("two").value;
        var userWords=sentence.split(" ");
        while(t<userWords.length){
            alert(userWords[t]);
            t++
        };
        x = 0;
        for (var x = 0; x < userWords.length; x++){
            y = 0;
            for (var y = 0; y < vocab.length; y++){

                if (y<vocab.length) {
                    y++
                };
                else if (vocab[y] == userWords[x]){
                    y = 0;
                    x++
                };
                else if(y<vocab.length) {
                    y++
                };
                else if (y == vocab.length){
                    y = 0;
                };
                else if (y == 0)
                {
                    vocab.push(userWords[x]);
                    x++
                };

            };


        };
    };

重申一下,据我所知,问题肯定出在 if else 部分,当它被删除或更改为更简单时,它突然起作用了。

【问题讨论】:

  • else 之前丢失;。可以在浏览器的 Web 开发人员工具中看到类似这样的细微语法错误(通常按 F12)。
  • 注意,第二个if (y &lt; vocab.length)(第三个if)没用。即使修复了这段代码,它也永远不会运行;第一个 if 已经处理了导致它运行的条件。
  • 哦,我不知道 F12 快捷键,谢谢你的信息。我将删除第三个 if 语句,谢谢:)

标签: javascript arrays function if-statement


【解决方案1】:

@DCoder 正确,需要去掉多余的;

HTML:

<input type="text" id="two" value="What the hell is wrong here??" />​

JavaScript:

wordSplit();

function wordSplit() {
    var vocab = [];
    var sentence = document.getElementById("two").value;
    var userWords = sentence.split(" ");
    var t = 0;
    while (t < userWords.length) {
        alert(userWords[t]);
        t++
    };
    x = 0;
    for (var x = 0; x < userWords.length; x++) {
        y = 0;
        for (var y = 0; y < vocab.length; y++) {

            if (y < vocab.length) {
                y++
            } else if (vocab[y] == userWords[x]) {
                y = 0;
                x++
            } else if (y < vocab.length) {
                y++
            } else if (y == vocab.length) {
                y = 0;
            } else if (y == 0) {
                vocab.push(userWords[x]);
                x++
            }

        }


    }
}​

Fixed Live Demo

【讨论】:

  • 谢谢!那行得通,所以 ;把一切都搞砸了?非常感谢您的更正:)
猜你喜欢
  • 2019-01-10
  • 1970-01-01
  • 1970-01-01
  • 2020-10-02
  • 2021-08-05
  • 1970-01-01
  • 2015-09-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多