我知道javascript函数可以使用任意数量的参数,可以通过arguments[i]
访问。我想知道是否可以将该数组转换为单个参数以发送到另一个也处理变量参数列表的函数。
我对字符串类有以下扩展,基本上格式化字符串,类似于string.format()在.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;
};
我有另一个需要获取javascript对象并将要处理的属性发送到字符串的函数。属性由调用函数设置。这是我想要获得的用法示例。我只是坚持将属性作为上述函数的单独参数传递。关于如何实现这一点的任何想法?
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('; ');
}
答案 0 :(得分:3)
其他答案是正确的,但只是明确地显示arguments
链:
function one() {
two.apply(this, arguments);
}
function two() {
console.log(arguments);
}
one("one", "two", "three");
打印:
["one", "two", "three"]
答案 1 :(得分:0)
var yourArguments = ['foo', 'bar'];
formatString.format.apply(formatString, yourArguments);
// equivalent to 'formatString.format('foo', 'bar')
所以,你的功能可能是:
function formatTheString(data, formatString, propertyList){
var myStrings = [];
data.forEach(function(item){
myStrings.push(item.format.apply(item, propertyList));
};
return myStrings.join('; ');
}
答案 2 :(得分:0)
不确定。使用apply()
var args = ['arg1', 'arg2'];
fn.apply(this, args);
相当于
fn('arg1', 'arg2');
答案 3 :(得分:0)
我只想将此作为我的最终工作解决方案,希望它能帮助某人。我在OP中的原始思想存在一些逻辑错误。
var MyClass = {
loadSupportArticles: function() {
var itemMarkupFormat = '<tr class="row-link single-cell"><td><a href="support-page.html/{0}">{1}</a></tr>';
var $supportAriclesList = $('#support-panel tbody');
this.populateTableFromAjaxResult(
'/support/Popular',
$supportAriclesList,
itemMarkupFormat,
['ArticleId', 'Title']);
},
loadUsers: function() {
var itemMarkupFormat = '<tr class="row-link"><td><a href="edit-user.html/{0}">{1}</a></td><td>{2}</td></tr>';
var $userSummaryList = $('#users-panel tbody');
this.populateTableFromAjaxResult(
'/accountuser/AccountUsersAsync',
$userSummaryList,
itemMarkupFormat,
['Id', 'Name', 'Type']);
},
// the part you guys helped with
getListItems: function(data, formatString, propertyNames) {
var completeList = [];
// for each data item
for (var i = 0; i < data.length; i++) {
// get values for each argument
var args = [];
for (var j = 0; j < propertyNames.length; j++) {
var propertyName = propertyNames[j];
args.push(data[i][propertyName]); // e.g. data[0]["PropName"]
}
// apply the template
completeList.push(formatString.format.apply(formatString, args));
}
return completeList.join('');
},
populateTableFromAjaxResult: function(url, $target, formatString, propertyNames) {
$target.empty();
$.ajax({
url: url,
type: 'GET',
accept: 'application/json',
success: function(data) {
var formattedData = MyClass.getListItems(data, formatString, propertyNames);
$target.append(formattedData);
}
});
}
}