var hasDuplicates = "eyes";
var noDuplicates = new Set(hasDuplicates); // {"e", "y", "s"}
console.log(Object.keys(noDuplicates)); // []
console.log(Object.values(noDuplicates)); // []
我基本上想访问名为“ noDuplicates”的集合中的“ e”,“ y”和“ s”。
var setToArray = [];
for (spot in noDuplicates) {
setToArray.push(Object.keys(noDuplicates)[spot])
}
答案 0 :(得分:2)
您可以使用array spread syntax将Set转换为数组:
var hasDuplicates = "eyes";
var noDuplicates = new Set(hasDuplicates); // {"e", "y", "s"}
var setToArray = [...noDuplicates];
console.log(setToArray);
您还可以使用Set.forEach()
或for...of loop直接访问Set的值:
var hasDuplicates = "eyes";
var noDuplicates = new Set(hasDuplicates); // {"e", "y", "s"}
noDuplicates.forEach(v => console.log(v));
for(const v of noDuplicates) {
console.log(v);
}
答案 1 :(得分:1)
noDuplicates
是一个提供迭代器的Set。只需使用for...of
或扩展运算符[... noDuplicates]
而不是for...in
。更好的是,直接使用Array.from
将集合转换为数组:
let setToArray = Array.from(new Set([1, 1, 1, 2, 2]));
console.log(setToArray);
答案 2 :(得分:0)
您还可以使用Array.from() Method在Set和Array之间进行转换:
var hasDuplicates = "eyes";
var noDuplicates = new Set(hasDuplicates);
var setToArray = Array.from(noDuplicates);
console.log(setToArray);