简体   繁体   English

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

[英]How to access an object with no keys, only values javascript

var hasDuplicates = "eyes";
var noDuplicates = new Set(hasDuplicates); // {"e", "y", "s"}


console.log(Object.keys(noDuplicates));   // []
console.log(Object.values(noDuplicates)); // []

I basically want to access the 'e', 'y', and the 's' of the set called 'noDuplicates'.我基本上想访问名为“noDuplicates”的集合的“e”、“y”和“s”。

var setToArray = [];
for (spot in noDuplicates) {
    setToArray.push(Object.keys(noDuplicates)[spot])
}

You can use array spread syntax to convert a Set to array: 您可以使用数组扩展语法将Set转换为数组:

 var hasDuplicates = "eyes"; var noDuplicates = new Set(hasDuplicates); // {"e", "y", "s"} var setToArray = [...noDuplicates]; console.log(setToArray); 

You can also use Set.forEach() or a for...of loop to access the Set's values directly: 您还可以使用Set.forEach()for ... of循环直接访问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); } 

noDuplicates is a Set which provides an iterator. noDuplicates是一个提供迭代器的Se​​t。 Simply use for...of or the spread operator [... noDuplicates] instead of for...in . 只需使用for...of或扩展运算符[... noDuplicates]而不是for...in Better yet, convert your set into an array directly with Array.from : 更好的是,使用Array.from将您的集合直接转换为数组:

 let setToArray = Array.from(new Set([1, 1, 1, 2, 2])); console.log(setToArray); 

You can also use the Array.from() Method to convert between a Set and an Array: 您还可以使用Array.from()方法在Set和Array之间进行转换:

 var hasDuplicates = "eyes"; var noDuplicates = new Set(hasDuplicates); var setToArray = Array.from(noDuplicates); console.log(setToArray); 

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM