admin管理员组文章数量:1391850
I want to print a string in following manner 'abc',21,'email' in javascript how can I do. below is my code.
var data = [];
data.push('abc');
data.push(21);
data.push('email');
I want to print a string in following manner 'abc',21,'email' in javascript how can I do. below is my code.
var data = [];
data.push('abc');
data.push(21);
data.push('email');
Share
Improve this question
edited Jan 19, 2016 at 7:21
thefourtheye
240k53 gold badges466 silver badges501 bronze badges
asked Jan 19, 2016 at 7:19
Vikas UpadhyayVikas Upadhyay
211 gold badge1 silver badge2 bronze badges
3 Answers
Reset to default 2Write a function to quote a string:
function quote(s) {
return typeof s === 'string' ? "'"+s+"'" : s;
}
Now map your array and paste the elements together with a ma:
data . map(quote) . join(',')
Since joining with a ma is the default way to convert an array into a string, you might be able to get away without the join
in some situations:
alert (data . map(quote));
since alert
converts its parameter into a string. Same with
element.textContent = data . map(quote);
if data is an array defined as
var data = [];
data.push('abc');
data.push(21);
data.push('email');
the use join() method of array to join (concatenate) the values by specifying the separator
try
alert( "'" + data.join("','") + "'" );
or
console.log( "'" + data.join("','") + "'" );
or simply
var value = "'" + data.join("','") + "'" ;
document.body.innerHTML += value;
Now data = ['abc', 21, 'email'];
So we can use forEach
function
var myString = '';
data.forEach(function(value, index){
myString += typeof value === 'string' ? "'" + value + "'" : value;
if(index < data.length - 1) myString += ', ';
});
console.log(myString)
Shorter version:
myString = data.map(function(value){
return typeof value === 'string' ? "'" + value + "'" : value;
}).join(', ');
console.log(myString);
JSFiddle: https://jsfiddle/LeoAref/ea5fa3de/
本文标签: How I can print string in javascriptStack Overflow
版权声明:本文标题:How I can print string in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744771230a2624351.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论