如何访问没有键,只有值的对象

时间:2019-01-02 22:19:03

标签: javascript arrays object set

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])
}

3 个答案:

答案 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是一个提供迭代器的Se​​t。只需使用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);