Reputation: 33
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?
Upvotes: -1
Views: 91
Reputation: 812
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 incremented twice so loop executed 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!"
);
Upvotes: 0
Reputation: 51
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.
Upvotes: 0
Reputation: 1402
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 a j);
for(var j=1;j<arr.length;j++){
str.push(arr[j]);
}
Upvotes: 0
Reputation: 44
Javascript does not have block scope.. change your other var i to something else
Upvotes: 0