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.
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.
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.
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.
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.
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(' '));
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With