最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript:array to string in javascript:enclosed with single quotes - Stack Overflow

programmeradmin0浏览0评论

I have an array like this

var array = ["f","test"];
var string =array.toString();

excepted string var string ='f','test';

current value: f,test

I have an array like this

var array = ["f","test"];
var string =array.toString();

excepted string var string ='f','test';

current value: f,test

Share Improve this question asked Apr 27, 2017 at 7:52 JabaaJabaa 1,7537 gold badges36 silver badges63 bronze badges 2
  • please fix the typo and add a bit more info or context – Montagist Commented Apr 27, 2017 at 7:54
  • Writing this question took so much more time than simply googling the answer. Why? – 1252748 Commented Apr 28, 2017 at 13:56
Add a comment  | 

6 Answers 6

Reset to default 10

You almost had it. Try this:

array.map(x => "'" + x + "'").toString();

Variable names like array and string are probably...akin to bad etiquitte, but I got'chu:

var anArray = [ "f", "test" ];
var theString = "'" + anArray.join("','") + "'";

Using ES6 with string interpolation and arrow function.

You can use join() or toString() to display each item separated by a comma

var array = ["f","test"];
console.log(array.map(x=>`'${x}'`).join(','))
console.log(array.map(x=>`'${x}'`).toString())

Let's use Map in JS

var result = ["f","test"].map(function(b) { 
   return "'" + b + "'"; 
}); 
console.log(result.toString());

1. using JavaScript Array.join() method : It will join all elements of an array into a string.

DEMO

var array = ["f","test"];

var res = "'"+array.join("','")+"'";

console.log(res);

2. using ES6 spread(...) operator : It allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) or multiple variables (for destructuring assignment) are expected.

DEMO

let array = ["f","test"];

function printString(a,b) {
  var str = `'${a}','${b}'`;
  return str;
}

var res = printString(...array);
console.log(res);

3. using Array.map() method with ES6 syntax - It creates a new array with the results of calling a provided function on every element in this array.

DEMO

var array = ["f","test"];

var str = array.map(item => "'" + item + "'").join();

console.log(str);

I believe you want your ouptut as a string and not as array and code to be written such that it is supported by all browser (no ES6). So I have tried to keep it as simple as possible:

var arrayTest = ["f","test"]
var str  = arrayTest.map(function(obj) {return("'" + obj + "'")}).toString();
发布评论

评论列表(0)

  1. 暂无评论