I know that javascript functions can take an arbitrary number of arguments which can be accessed via arguments[i]. I'm wondering if it is possible to convert that array into individual arguments to send to another function that also processes a variable list of arguments.
I have the following extension to the string class that basically formats strings similar to how string.format() works in .Net.
String.prototype.format = String.prototype.format = function () {
var s = this,
i = arguments.length;
while (i--) {
s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
}
return s;
};
I have another function that needs to take a javascript object and send properties to be processed into a string. The properties are set by the calling function. Here is an example of the usage I am trying to get. I'm simply stuck at passing the properties through as individual arguments to the function above. Any ideas on how to come about this?
function doMything(){
var myData = GetMyDataFromSomething(); // returns a javascript array of objects
var myMessageFormat1 = 'Person with ID {0} name is {1} {2}';
var myPropertyList1 = ['UserID', 'FirstName', 'LastName']
var finishedStrings1 = formatTheString(myData, myMessageFormat1, myPropertyList1);
// ex. Person with ID 45 name is Jake Gyllenhal; Person with ID 46 name is Bob Barker
var myMessageFormat2 = '{0} is from {1}, {2}';
var myPropertyList2 = ['FirstName', 'City', 'State']
var finishedStrings2 = formatTheString(myData, myMessageFormat2, myPropertyList2);
// ex. Jake is from Phoenix, AZ; Bob is from San Diego, CA
}
function formatTheString(data, formatString, propertyList){
var myStrings = [];
data.forEach(function(item){
myStrings.push(item.format(propertyList)); // this doesn't work because the object is passed as a single argument
};
return myStrings.join('; ');
}
anotherfunction.apply(context, arguments);--- is this what you want?