开发者

creating a for-loop using Javascript?

I have a problem creating a for-loop using Javascript. It seems everyting is fine for me but still I didn't get what I want.

Take a look please to this code to understand more:

  • The HTML form code:

    <form name="myform">
        <textarea name="inputtext" cols="100%" rows="10%"></textarea><br />
        <input type="radio" name="options" value="javascript" checked> Option1 <br />
        <input type="radio" name="options" value="windows"> Option2<br />
        <input type="button" value="Do it" onClick="generate();"><br />
        <textarea name="outputtext" cols="100%" rows="10%"></textarea><br />
    </form>
    
  • The Javascript code:

    fu开发者_如何学Cnction generate() {
    var code = ""+document.myform.inputtext.value;
    if (document.myform.options[0].checked) {
        document.myform.outputtext.value = escape(code);
    }
    else {
        var result= "2- ";
        for(int i=0; i<code.length; i++) {
        //There will be some logic to decide if to add the char or not.
        result+=code.charAt(i);
        }
        document.myform.outputtext.value = result;
    }
    }
    

The problem is not clear for me. However, when I try to comment out the for-loop, everything works fine !

Any ideas?


There is no int data type in Javascript (or any data types at all used to declare variables).

for(var i=0; i<code.length; i++) {


There is also an Object-oriented solution to this.

var generate = {
   loop: function() {
        var code = ""+document.myform.inputtext.value;

        if (document.myform.options[0].checked) {
            document.myform.outputtext.value = escape(code);
        }
        else {
            var result= "2- ";
            //CHANGE THE INT(I assume Java) DATATYPE TO A LOCAL VARIABLE USING THE var KEYWORD TO KEEP THE SCOPE IN THE FOR LOOP
            //RECURSION CAN BE QUICKER
            for(var i=0; i<code.length; i++) {
            //There will be some logic to decide if to add the char or not.
            result+=code.charAt(i);
        }
        document.myform.outputtext.value = result;
     }
 }

generate.loop();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜