Converting a Javascript array to a function arguments list
July 30th, 2010
No comments
1.at the beginning, use “eval”, eval is not safe if raise error, it only show something wrong in eval. we should find the real problem by self.
function dynamic_call(func, params){
var tmpArray = [], text = "window[func](";
for(var i=0;i
tmpArray.push("params[ "+ i + "]");
}
text += tmpArray.join();
text += ")"
alert(text)
return eval(text);
}
dynamic_call("alert", ["haha"])
2. another way use apply
apply like call. but apply support array as arguments
window["alert"].apply(window, ["haha"])
window["alert"].call(window, "haha")
// it also work like this
function Model(){
}
Model.alert = function(){
alert("model alert" + arguments[0])
}
Model["alert"].apply(Model, ["haha"])