Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print set element in javascript

I am trying to print the set element through innerHTML, but I am not getting the desired result. While I tried with document.write(),it is printing but I want to use only innerHTML.

Here is my source code:

  <div id="demo"> </div>  
  <script type="text/javascript">
     var i, item;
     var setObj1 = new Set();
     for(i=0;i<5;i++)
     setObj1.add(i);

     for (item of setObj1.values())
     //document.write(item+",");
     document.getElementById('demo').innerHTML="The set value is: "+ item;         
  </script>

Output: 4

Desire output: 0 1 2 3 4

Please suggest me how to use innerHTML to print the output.I have tried console log and document.write(), they are working.

like image 533
Ratnesh Avatar asked Feb 04 '19 06:02

Ratnesh


People also ask

How do you print an element in JavaScript?

JavaScript does not have any print object or print methods. You cannot access output devices from JavaScript. The only exception is that you can call the window.print() method in the browser to print the content of the current window.

What is Set () in JavaScript?

A JavaScript Set is a collection of unique values. Each value can only occur once in a Set. A Set can hold any value of any data type.

How do I print a specific div?

To print the content of div in JavaScript, first store the content of div in a JavaScript variable and then the print button is clicked. The contents of the HTML div element to be extracted.

How do you print a collection in JavaScript?

To correctly display an array of objects, we need to format the array as a JSON string. JSON. stringify() formats the array and gives the correct print. We can use a <pre> tag to display the output.


2 Answers

You can also achieve it by converting to an array using the spread operator and then joining, if you're looking for a one liner:

// Establishing a set 
let mySet = new Set(['a', 'b', 'c']);

// Printing the set, space delimited 
console.log(new Array(...mySet).join(' '));
like image 94
jlents Avatar answered Nov 01 '22 10:11

jlents


if you want to avoid traditional looping you could also use Array#from

const set = new Set(1,2,3)

console.log(
  Array.from(set.values())
)

also works better for non-browser targets like node where the output of Set is shortened

like image 31
lfender6445 Avatar answered Nov 01 '22 11:11

lfender6445