46

如何将数组加入字符串并同时将每个值包含在其中

'1/2/12','15/5/12'

for (var i in array) {
    dateArray.push(array[i].date);
}
dateString=dateArray.join('');
console.log(dateString);
4

3 回答 3

126

如果您的日期已经是字符串,您可以执行以下操作

var dates = ['1/2/12','15/5/12'];

console.log("'" + dates.join("','") + "'");

然而,一个更酷、更简单的方法(对于没有日期的情况)方法是 Array.prototype.map

// Array.prototype.map returns a new array by 
// mapping each element in the existing array
dates.map(function(date){
    // Wrap each element of the dates array with quotes
    return "'" + date + "'";
}).join(","); // Putsa comma in between every element

或者用 es6 术语

dates.map(date => `'${date}'`).join(',');

http://jsfiddle.net/yMvVh/

于 2012-08-02T01:24:14.223 回答
16

ES6:

var dates = ['1/2/12','15/5/12'];
var result = dates.map(d => `'${d}'`).join(',');
console.log(result);

于 2017-12-22T10:24:55.477 回答
4
dateString = '\'' + dateArray.join('\',\'') + '\'';

演示:http: //jsfiddle.net/mLRMb/

于 2012-08-02T01:22:34.563 回答