简体   繁体   中英

Can someone tell me what's wrong with this javascript?

I am trying something experimental here, please answer, what's wrong in this code?

function run(){
 for(var i=0;i<arguments.length;i++){
  var type=arguments[i].split(" ")[0];
   if(type=="(write)"){
    var arr=arguments[i].split(" ");
    var str=[];
    for(var i=1;i<arr.length;i++){
     str.push(arr[i]);
    }
    var fin="\n"+str.join(" ");
    document.getElementById("console").textContent+=fin;
   }
  }
 }
run(
 "(write) I wonder if this works.",
 "(write) I think it DOES!"
);

Somehow it only puts "I wonder if this works." in the div but no "I think it DOES!". Can someone tell me what's wrong and return the corrected script?

JavaScript没有代码块范围..将其他变量更改为其他内容

You are using i variable of for loop twice. Javascript has functional scope and block scope. So use different variable in second "for" (may be aj);

for(var j=1;j<arr.length;j++){
     str.push(arr[j]);
    }
function run(){


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


    var type=arguments[i].split(" ")[0];
    if(type=="(write)"){
      var arr=arguments[i].split(" ");

      var str=[];

      //here your i was increamented twice so loop excuted only once
      for(var j=1;j<arr.length;j++){
       str.push(arr[j]);
     }


     var fin="\n"+str.join(" ");
     console.log(fin);
     document.getElementById("console").textContent+=fin;
   }
 }
}
run(
 "(write) I wonder if this works.",
 "(write) I think it DOES!"
 );

Change i in loop in:

for (var i = 1; i < arr.length; i++){
    str.push(arr[i]);
}

by something else or use let in es6 to define i.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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