Friday, May 10, 2024
150
rated 0 times [  153] [ 3]  / answers: 1 / hits: 20836  / 8 Years ago, wed, april 13, 2016, 12:00:00

Please have a look at the below script. I am testing it with Chrome.



/*declare a new set*/
var items = new Set()

/*add an array by declaring as array type*/
var arr = [1,2,3,4];
items.add(arr);

/*print items*/
console.log(items); // Set {[1, 2, 3, 4]}

/*add an array directly as argument*/
items.add([5,6,7,8]);

/*print items*/
console.log(items); // Set {[1, 2, 3, 4], [5, 6, 7, 8]}

/*print type of items stored in Set*/
for (let item of items) console.log(typeof item); //object, object

/*check if item has array we declared as array type*/
console.log(items.has(arr)); // true

/*Now, check if item has array we added through arguments*/
console.log(items.has([5,6,7,8])); //false

/*Now, add same array again via argument*/
items.add([1,2,3,4]);

/*Set has duplicate items*/
console.log(items); // Set {[1, 2, 3, 4], [5, 6, 7, 8], [1, 2, 3, 4]}



  1. Why it is returning false at items.has([5,6,7,8])?

  2. Why it is allowing duplicate values? I thought A set is in an ordered list of values that cannot contain duplicates

  3. How to access array added by items.add([5,6,7,8])?


More From » ecmascript-6

 Answers
20

  1. Why it is returning false at items.has([5,6,7,8])?



    From MDN




    The Set object lets you store unique values of any type, whether primitive values or object references.




    The objects are compared using the reference, not the value. Sets uses SameValueZero(x, y) comparison algorithm to compare values. It says Return true if x and y are the same Object value. Otherwise, return false.


  2. Why it is allowing duplicate values? I thought A set is in an ordered list of values that cannot contain duplicates



    Same as #1. An non-primitive value is said to be already exists in set if the same object(not just same looking) already added in the set.


  3. How to access array added by items.add([5,6,7,8])?



    You've to create a variable and add the variable to the set. Then this variable can be used to check if set has that array or not.



[#62581] Monday, April 11, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
byronkodyo

Total Points: 552
Total Questions: 87
Total Answers: 104

Location: Burundi
Member since Sat, Aug 21, 2021
3 Years ago
;