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

In Javascript, how do I put single quotes around an array I just "joined"? - Stack Overflow

programmeradmin9浏览0评论
[3, 4, 5]
['4', '1', 'abc123']


function bine_ids(ids){
    return ids.join(',');
};

No matter what type of list, I want my function to return a string with single quotes around the elements.

The function should return:

'3','4','5'

and

'4','1','abc123'

I want my resulting string to have single quotes in them!

[3, 4, 5]
['4', '1', 'abc123']


function bine_ids(ids){
    return ids.join(',');
};

No matter what type of list, I want my function to return a string with single quotes around the elements.

The function should return:

'3','4','5'

and

'4','1','abc123'

I want my resulting string to have single quotes in them!

Share Improve this question asked Dec 6, 2011 at 22:42 TIMEXTIMEX 272k367 gold badges800 silver badges1.1k bronze badges
Add a ment  | 

3 Answers 3

Reset to default 16

Simple logic!

function bine_ids(ids) {
  return (ids.length ? "'" + ids.join("','") + "'" : "");
}
console.log(bine_ids([]));
console.log(bine_ids([3]));
console.log(bine_ids([3, 4, 'a']));

Example output:

(an empty string)
'3'
'3','4','a'

how do I put single quotes around an array I just “joined”?

Your approach seems to be unnecessarily plex. You better off:

  1. Create intermediate array with all elements converted toString and quoted
  2. join the intermediate array

[03:22:35.728] [3, 4, 5].map( function (element) { return "'" + String(element) + "'" } ).join(",")
[03:22:35.736] "'3','4','5'"
--
[03:22:58.925] ['4', '1', 'abc123'].map( function (element) { return "'" + String(element) + "'" } ).join(",")
[03:22:58.933] "'4','1','abc123'"

Note: map method required JS 1.6+, versions below are requiring you to iterate an array "manually":

function bine_ids( array ) {
  var tmp = [];
  for ( var i = 0; i < array.length; i++ ) {
    tmp[i] = "'" + String( array[i] ) + "'";
  }
  return tmp.join(",");
}

Like:

 function myjoin(arr) {
   return "'" + arr.join("','") + "'";
 }

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论