如何将值合并为String格式

时间:2011-04-06 15:46:04

标签: javascript

  

可能重复:
  Merging Values into an Array

3 个答案:

答案 0 :(得分:4)

您是否可以控制这些变量的名称?如果是这样,我会改变他们的结构:

var names = {
    AppointmentSearchDays: 'aaa',
    AppointmentSearchDaysBefore: 'bbb',
    PrimeSuiteId: 'ccc'    
};

var values = {
    AppointmentSearchDays: 3333,
    AppointmentSearchDaysBefore: 5,
    PrimeSuiteId: 10 
};

这将允许您像这样合并它们:

var arr = [];
for (var key in names) {
    if (names.hasOwnProperty(key)) {
        arr.push(names[key] + ' ' + values[key]);
    }
}

arr.join(',');

如果你想获得真正的大胆,你可以这样做:

var values = {
    AppointmentSearchDays: { key: 'aaa', value: 3333 },
    AppointmentSearchDaysBefore: { key: 'bbb', value: 5 }
    PrimeSuiteId: { key: 'ccc', value: 10 }
};


var arr = [];
for (var i = 0, len = values.length; i < len; i++) {
    arr.push(values[i].key + ' ' + values[i].value);
}

arr.join(',');

答案 1 :(得分:2)

我可能过度简化了问题,但只使用原生连接运算符+

var format = var AppointmentSearchDaysAfter
 + ' '
 + AppointmentSearchDaysAfterValue
 + ','
 + AppointmentSearchDaysBefore
 + ' '
 + AppointmentSearchDaysBeforeValue
 + ','
 + PrimeSuiteId
 + ' '
 + PrimeSuiteIdValue
alert(format);

答案 2 :(得分:1)

您只需使用“+”运算符附加所有值:

实际字符串:

var result = AppointmentSearchDaysAfter + " " + AppointmentSearchDaysAfterValue + "," +AppointmentSearchDaysBefore + " " + AppointmentSearchDaysBeforeValue  + "," + PrimeSuiteId + " " + PrimeSuiteIdValue;

可读字符串:

var result = AppointmentSearchDaysAfter + " " + 
                 AppointmentSearchDaysAfterValue + "," +
                 AppointmentSearchDaysBefore + " " + 
                 AppointmentSearchDaysBeforeValue  + "," + 
                 PrimeSuiteId + " " + 
                 PrimeSuiteIdValue;