How I can print string in javascript - Stack Overflow

I want to print a string in following manner 'abc',21,'email' in javascript how can

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
Add a ment  | 

3 Answers 3

Reset to default 2

Write 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/

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744771231a4592771.html

相关推荐

  • How I can print string in javascript - Stack Overflow

    I want to print a string in following manner 'abc',21,'email' in javascript how can

    15小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信