Javascript 加入数组用引号括起来每个值javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11769774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:01:35  来源:igfitidea点击:

join array enclosing each value with quotes javascript

javascriptarrays

提问by dll_onFire

How can join an array into a string and at the same time enclosing each value into this '1/2/12','15/5/12'

如何将数组加入字符串并同时将每个值包含在此 '1/2/12','15/5/12' 中

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

回答by Juan Mendes

If your dates are already strings, you can do the following

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

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

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

However, a cooler and more foolproof way (for the case with no dates) way would be Array.prototype.map

然而,一种更酷、更万无一失的方式(对于没有日期的情况)方式是 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

Or in es6 lingo

或者在 es6 行话中

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

http://jsfiddle.net/yMvVh/

http://jsfiddle.net/yMvVh/

回答by Ianp

ES6:

ES6:

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

回答by Pedro L.

dateString = '\'' + dateArray.join('\',\'') + '\'';

demo: http://jsfiddle.net/mLRMb/

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