简体   繁体   English

将JavaScript集转换为字符串的最有效方法

[英]The most efficient way to convert a javascript set to string

Is there a way of converting a Set to a String directly (without first converting the set to an array)? 有没有一种方法可以将Set直接转换为String(无需先将Set转换为数组)? I have gone through the documentation at Mozilla and I feel they may be a way of doing it. 我已经浏览了Mozilla的文档,并且我认为它们可能是实现此目的的一种方法。 This is what I do: 这是我的工作:

let myset = new Set();
myset.add(3);
myset.add(" Wise ");
myset.add(" Men ");

let setStr = myset.toString();
let setArrStr = Array.from(myset).toString();

console.log("Set to String: " + setStr );  //"Set to String: [object Set]"
console.log("Set to Array to String: " + setArrStr);  // "Set to Array to String: 3, Wise , Men "

You can convert to string directly like so: 可以像这样直接转换为字符串:

 let string = ""; let myset = new Set(); myset.add(3); myset.add(" Wise "); myset.add(" Men "); myset.forEach(value => string += value); console.log(string); // → "3 Wise Men " 

Hope you got your answer. 希望你能得到答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Javascript:将字符串转换为整数然后再转换回字符串的最有效方法 - Javascript: Most Efficient way to convert string to integer then back to string 将字符串转换为数字的最有效方法是什么? - What is the most efficient way to convert a string to a number? 在Javascript中解析复杂字符串的最有效方法 - Most efficient way to parse a complex string in Javascript 在javascript中将整数转换为数字的小数部分的最有效方法是什么? - What is the most efficient way to convert an integer to the fractional part of a number in javascript? 使用纯javascript设置样式的最有效方法? - Most efficient way to set style using pure javascript? 使用JavaScript评估字符串是否是回文符的最有效方法是什么? - What's the most efficient way to evaluate if a string is a palindrome using Javascript? 使用 javascript 呈现字符串模板的最有效方法 - Most efficient way for rendering string templates using javascript 在Java中通过字符串的最有效方式是什么? - What is the most efficient way to go through string's chars in Javascript? 返回包含字符串的嵌套数组的最有效方法 (JavaScript) - Most efficient way to return a nested array that includes a string (JavaScript) 比较两个字符串数组Javascript的最快/最有效的方法 - Fastest / most efficient way to compare two string arrays Javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM