javascript 如何将 Set 转换为带空格的字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47243139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert Set to string with space?
提问by KimchiMan
I want to convert JavaScript Setto stringwith space.
我想将 JavaScript 转换Set为string带空格的。
For example, if I have a set like:
例如,如果我有一个像:
var foo = new Set();
foo.add('hello');
foo.add('world');
foo.add('JavaScript');
And I'd like to print the string from the set: hello world JavaScript(space between each element).
我想从集合中打印字符串:(hello world JavaScript每个元素之间的空格)。
I tried below codes but they are not working:
我尝试了以下代码,但它们不起作用:
foo.toString(); // Not working
String(foo); // Not working
Is there simplest and easiest wayto convert from Setto string?
有没有最简单的方法可以从Set转换为string?
回答by Mihai Alexandru-Ionut
You can use Array.from:
您可以使用Array.from:
Array.from(foo).join(' ')
or the spread syntax:
或传播语法:
[...foo].join(' ')
回答by Ketan Ramteke
You can iterate through the set and build an array of the elements and return the desired string by joining the array.
您可以遍历该集合并构建一个元素数组,并通过加入该数组返回所需的字符串。
var foo = new Set();
foo.add('hello');
foo.add('world');
foo.add('JavaScript');
let strArray = [];
for(str of foo){
strArray.push(str);
}
console.log(strArray.join(" "));

