【发布时间】:2021-12-20 02:31:02
【问题描述】:
const set = new Set("123");
console.log(set);
输出是“设置{'1','2','3'}”
【问题讨论】:
标签: javascript string set
const set = new Set("123");
console.log(set);
输出是“设置{'1','2','3'}”
【问题讨论】:
标签: javascript string set
因为字符串是iterable,当你给the Set constructor 一个可迭代对象时,它会循环遍历对象迭代器提供的值并将它们添加到集合中。对于字符串,string iterator 迭代字符串代码点 - 在您的示例中,"1"、"2" 和 "3"。 (有关“代码点”与“代码单元”以及字符串是什么的更多信息,请阅读my blog post。)
如果要将字符串添加到集合中,则必须单独添加或将其包装在另一个可迭代对象中(如数组):
// Add separately:
let set = new Set();
set.add("123");
console.log(set.size); // 1
console.log([...set]); // ["123"]
// Or wrap:
set = new Set(["123"]);
console.log(set.size); // 1
console.log([...set]); // ["123"]
¹(或一个原语,如强制转换为可迭代对象的字符串)
【讨论】:
Set constructor 采用 an iterable 并采用它的每个值。
字符串have an @@iterator property by default 使其可迭代:
const foo = "xyz";
console.log(...foo);
const [a, b, c] = foo;
console.log(a, b, c);
for (const char of foo)
console.log(char);
因此,当您将字符串传递给 Set 构造函数时,这正是发生的情况 - 它绘制每个值,就像使用任何其他可迭代对象一样:
const foo = "xyz";
const bar = [1, 2, 3]
console.log("set of string:", new Set(foo));
console.log("set of array :", new Set(bar));
<h1>Check the browser console</h1>
【讨论】: