Search code examples
javascriptdocument.write

Output issues with document.write


I am trying to write a javascript that counts the number of negative, zero, and positive numbers in an array. When I run this script it says "ReferenceError: document is not defined"

I don't know how to define document, because it is my understanding that document.write is part of node.js? What is the best way to get it to output the neg, zero, and pos variables?

#!/usr/bin/env node

// Function: counter
// Parameter: -3, -1, 0, 0, 0, 4, 17, 29, 30
// Returns the number of each in the array
var input = new Array(-3, -1, 0, 0, 0, 4, 17, 29, 30);
var zero = 0;
var neg = 0;
var pos = 0;

function counter(input, zero, neg, pos)
{
    switch (input)
    {
       case (input < 0):
       neg++;
       break;

       case (input == 0):
       zero++;
       break;

       case (input > 0):
       pos++;
       break;
    } 

return document.write(neg, zero, pos);
}

 counter(input);

Solution

  • You need to cycle on all elements contained in the array, and if you call the function with only one argument I suggest to avoid to define the other three.

    The code is:

        var input = new Array(-3, -1, 0, 0, 0, 4, 17, 29, 30);
        var zero = 0;
        var neg = 0;
        var pos = 0;
    
        function counter(input) {
            input.forEach(function(ele) {
                switch (true) {
                    case (ele < 0):
                        neg++;
                        break;
                    case (ele == 0):
                        zero++;
                        break;
                    case (ele > 0):
                        pos++;
                        break;
                }
            });
        }
    
        counter(input);
    
        console.log(neg, zero, pos);