ES6 - Collections Set values() and keys()



The values method returns a new Iterator object that contains the values for each element in the Set object. The keys() function too behaves in the same fashion.

Syntax

mySet.values(); 
mySet.keys(); 

Return Value

A new Iterator object containing the values for each element in the given Set.

Example

var mySet = new Set(); 
mySet.add("Jim"); 
mySet.add("Jack"); 
mySet.add("Jane"); 
console.log("Printing keys()------------------");  

var keyitr = mySet.keys(); 
console.log(keyitr.next().value); 
console.log(keyitr.next().value); 
console.log(keyitr.next().value);  
console.log("Printing values()------------------"); 

var valitr = mySet.values(); 
console.log(valitr.next().value); 
console.log(valitr.next().value); 
console.log(valitr.next().value);

Output

Printing keys()------------------ 
Jim 
Jack 
Jane 
Printing values()------------------ 
Jim 
Jack 
Jane

Example: Iterating a Set

'use strict' 
let set = new Set(); 
set.add('x'); 
set.add('y'); 
set.add('z'); 

for(let val of set){ 
   console.log(val); 
}

The following output is displayed on successful execution of the above code.

x 
y 
z
Advertisements