lundi 23 juin 2014

javascript for loop unexpected results


Vote count:

0




I am using a function called partial which creates another function based on the arguments you give it. However for some reason i am getting unexpected results if inside the function i call a for loop like this without using var. for(i=1; i<knownArgs.length; i++) however when i call the for loop with using var as so for (var i = 1; i < knownArgs.length; i++) i get the result i expected. Here are the functions i am using and the result i expect.



var op = {
"+": function(a, b){return a+b;},
"==": function(a, b){return a == b;},
"===":function(a, b){return a === b;},
"!":function(a){return !a;}
};

function map(func, array){
var result = [];
forEach(array, function(element){
result.push(func(element));
});
return result;
}
function forEach(array, action){
for(i=0; i<array.length; i++){
action(array[i]);
}
}


function partial(func) {
var knownArgs = arguments;
return function() {
var realArgs = [];
for(i=1; i<knownArgs.length; i++){
realArgs.push(knownArgs[i]);
}
for(i=0; i<arguments.length; i++){
realArgs.push(arguments[i]);
}
return func.apply(null, realArgs);
};
}


console.log(map(partial(op["+"], 1), [0,2,4,6,8,10]));


When i make the call at the end i am expecting an array [1,3,5,7,9,11] and i do get that when inside the two for loops inside the partial() function have var i = #. However i have never used a var there before and can someone explain to me why when i do not use it i get an infinite loop that returns an array of 3s and 4s.



asked 2 mins ago






Aucun commentaire:

Enregistrer un commentaire