admin管理员组文章数量:1287942
[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 badges3 Answers
Reset to default 16Simple 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:
- Create intermediate array with all elements converted
toString
and quoted 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("','") + "'";
}
本文标签: In JavaScripthow do I put single quotes around an array I just quotjoinedquotStack Overflow
版权声明:本文标题:In Javascript, how do I put single quotes around an array I just "joined"? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1739866185a2201643.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论