如何在循环中调用函数

时间:2012-10-13 21:38:08

标签: javascript function loops function-call do-loops

我需要在循环中调用一个函数。

我有以下代码......

do {
    var name = prompt("Enter name:");

    if (!isNaN(age) && name != null && name != "") {
        names[i] = name;
    }
    loop = confirm("Add new name?");

    i++;
    // at this place I want to call the function
    // addnew(document.getElementById("newtable")"; so when someone clicks cancel in the confirm box the javascript creates a dynamic table from the array names
} while (loop);​

任何人都知道如何调用addnew函数?

2 个答案:

答案 0 :(得分:0)

我猜你确实想要在确认回答是的时调用该函数,并且当它没有可以像这样实现时终止循环:

while(true) {
    var name = prompt("Enter name:");
    if (!name) {
        break;
    }

    if (!isNaN(age)) {
        names[i] = name;

    }


    if (!confirm("Add new name?")) {
        break;
    }

    i++;
    // at this place I want to call the function
    addnew(document.getElementById("newtable")); 
}

答案 1 :(得分:0)

你想做这样的事情:

var name,
names = [];

function coolFunc(names) {
    console.log(names);
}

do {
    var name = prompt("Enter name:");

    if (name != null && name != "") {
        names.push(name);
    }
    loop = confirm("Add new name?");

//  if you want to handle the names one-by-one as you get them, then you could call 
//  your function here, otherwise call it when you exit the loop as below

} while (loop);

coolFunc(names);

我删除了age的测试,因为您发布的内容中没有任何内容表明它来自哪里,因此抛出错误,因此您需要在适当的时候重新开始工作,并且i似乎没有必要,但也犯了错误。