简体   繁体   English

在 javascript 中使用冒号作为分隔符

[英]Using a colon as a separator in javascript

var data = "needactivation:9";
if (data.indexOf(":") == true) {
    replyData = data.split(":");
    if (replyData[0] == "needactivation") {
        alert("User Id Is " + replyData[1]);
    }
}
else if (data == "success") {
    window.location.href = "/";
}
else {
    alert("Unknown error.");
}

Is my JavaScript.是我的 JavaScript。 It should alert the User ID but it gives a unknown Error.它应该提醒用户 ID,但它给出了一个未知的错误。 Any idea whats wrong with this script?知道这个脚本有什么问题吗?

Not sure if this part matters, but i'm using the latest jQuery on the page also.不确定这部分是否重要,但我也在页面上使用最新的 jQuery。

indexOf returns an index (or -1 if not found), not a boolean. indexOf返回一个索引(如果未找到则返回-1 ),而不是 boolean。 Change this:改变这个:

if (data.indexOf(":") == true) {

To this:对此:

if (data.indexOf(":") !== -1) {

Alternatively, you could split regardless and then check replyData.length .或者,您可以不顾一切地split ,然后检查replyData.length

String.indexOf() returns a number >= 0 when the string is found, not a boolean true value String.indexOf()找到字符串时返回一个数字 >= 0,而不是 boolean true

Your test should read:你的测试应该是:

if (data.indexOf(":") >= 0) {
    ...
}
var data = "needactivation:9";
if (data.indexOf(":") >= 0) {
    replyData = data.split(":");
    if (replyData[0] == "needactivation") {
        alert("User Id Is " + replyData[1]);
    }
}
else if (data == "success") {
    window.location.href = "/";
}
else {
    alert("Unknown error.");
}

Try if (data.indexOf(":") != -1) {试试if (data.indexOf(":") != -1) {

In addition to verifying that the above answers are correct, I just wanted to say that you may also want to employ some kind of try/catch logic once you've changed your true to -1 since a string like Anything: will have an indexOf(":") >= 0 but will split in such a way that your reference to replyData[1] will throw yet another error.除了验证上述答案是否正确之外,我只想说,一旦将true更改为-1 ,您可能还想使用某种 try/catch 逻辑,因为像Anything:都会有一个indexOf(":") >= 0但会以这样一种方式拆分,即您对replyData[1]的引用将引发另一个错误。

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

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