简体   繁体   English

为什么此JavaScript代码不起作用?

[英]Why this JavaScript code doesn't work?

I have for loop which goes through the array with arguments. 我有for循环,它通过带有参数的数组。 When next argument is "?", "&" or "||", it shouldn't add comma, however, it always adds. 当下一个参数是“?”,“&”或“ ||”时,它不应该添加逗号,但是总会添加。 I couldn't understand why, here is the code: 我不明白为什么,这是代码:

 var args = ["arg1","arg2","?","arg3"]; var query = ""; for (var i = 0; i < args.length; i++) { switch (args[i]) { case "?": query += " where "; break; case "&": query += " and "; break; case "||": query += " or "; break; default: if (args[i+1] != "?"); { query += args[i] + ", "; break; } query += args[i] + " "; break; } } document.write(query); 

When I type this (this is splitted by " " and sent to array args): 当我键入此内容时(这被“”分割并发送到数组args):

arg1 arg2 ? arg3

It prints it like this: 它像这样打印:

arg1, arg2, where arg3, // while it should be arg1, arg2 where arg3,

Thanks for helping people, problem was caused by an extern script. 感谢您的帮助,问题是由外部脚本引起的。 And yes, I removed semicolon ;) 是的, 我删除了分号;)

Your if statement is broken: 您的if语句已损坏:

        if (args[i+1] != "?"); // <---- remove that semicolon
        {
            query += args[i] + ", ";
            break;
        }

You've got a stray semicolon. 您有一个流浪的分号。 It is not a syntax error, but it means the if doesn't do anything. 这不是语法错误,但这意味着if不执行任何操作。 The code that adds the comma always runs, and exits the switch before the code that doesn't add the comma. 添加逗号的代码始终运行,并在添加逗号的代码之前退出switch

You have a semicolon between your if and your block: 如果if和您的代码块之间有分号:

if (args[i+1] != "?"); 

Should be 应该

if (args[i+1] != "?")

There may be completely different ways to solve this problem which would make your code easier to extend without deepening trees of if or switch 可能存在完全不同的方法来解决此问题,这将使您的代码更易于扩展,而无需加深ifswitch

A quick example, 一个简单的例子

// define some dictionaries
let logicDict = Object.assign(Object.create(null), {
    '?': 'where',
    '&': 'and',
    '||': 'or'
});

// define some flags
let noComma = false;

// reduce your array
['arg1', 'arg2', '?', 'arg3'].reduceRight((str, e) => {
    if (e in logicDict) {
        noComma = true;
        return logicDict[e] + ' ' + str;
    }
    if (!noComma) e += ',';
    noComma = false;
    return e + ' ' + str;
}, '').slice(0, -1);
// "arg1, arg2 where arg3,"

感谢您注意到分号,问题是由外部脚本引起的。

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

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