简体   繁体   English

如何在循环中调用函数

[英]How to call a function in a loop

I need to call a function in a loop. 我需要循环调用一个函数。

I have the following code.... 我有以下代码。

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);​

Anyone knows how I can call the function addnew? 有人知道我如何调用函数addnew吗?

I'm guessing that you want the function called when the Confirm answers yes and terminate the loop when it doesn't which could be implemented like this: 我猜想您要在Confirm回答为yes时调用该函数,并在没有回答时终止该循环,可以像这样实现:

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")); 
}

Are you looking to do something like this: 您是否要执行以下操作:

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);

I removed the test for age because there isn't anything in what you posted to indicate where that's coming from and so was throwing an error, so you'd need to work that back in as appropriate, and i didn't really seem necessary but was also throwing an error. 我删除了针对age的测试,因为您发布的内容中没有任何内容可以表明该内容来自何处,因此会引发错误,因此您需要适当地进行修改,而且i似乎没有必要但也引发了错误。

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

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