搜索缺少变量的数组

时间:2014-06-11 17:05:01

标签: javascript arrays loops

这就是我需要的,我只是想简化一下。我设计了这个我在互联网上找到的各种东西。问题是如果添加更多消息并且不调整循环中消息的数量,它最终会崩溃,我想解决这个问题。任何想法?

var chatMessages = [chatMessage0 = "",
chatMessage1 = " this",
chatMessage2 = " is",
chatMessage3 = " almost",
chatMessage4 = " perfect",
chatMessage5 = " for what I need",
chatMessage999 = ""];
var chatMessageCount = 5;
var chatNow = [];

chat();
function chat() {
    for (i = 0; i < chatMessageCount + 2; i++) {
        chatNow = chatMessages[i];
        if (chatNow.length > 0) {
            alert(chatNow);
        }
    }
}

Demo

1 个答案:

答案 0 :(得分:0)

您不需要chatMessageCount变量。只需使用chatMessages.length

var chatMessages = [
    "",
    " this",
    " is",
    " almost",
    " perfect",
    ""];

function chat() {
    for (var i = 0; i < chatMessages.length; i++) {
        var chatNow = chatMessages[i];
        if (chatNow != "") {
            alert(chatNow);
        }
    }
}

DEMO