Search code examples
jscript

JS file doesn't work


Here's the code in my JS file:

function arrayContains(array, value){
    return array.indexOf(value) > -1;
}
var possibleOptions = ["male", "female", "m", "f"];
var gender = prompt("What's your gender?","");
while(!arrayContains(possibleOptions, gender))
    gender = prompt("Invalid input. What's your gender?");
var name = prompt("What's your name?","");
var greeting = (gender == "male" || gender == "m") ? "Sup dude." : "Sup girl.";
alert("Hello, " + name + "! " + greeting);

The error I get:

Line: 5
char: 1
Object expected.

I can't figure it out.


Solution

  • Two problems:

    1. As mentioned in comments, the w/cscript.exe script host does not support neither prompt() nor alert()
    2. JScript arrays have no .IndexOf() method

    You have to roll your own:

    function arrayContains(array, value){
        for (var i = 0, e = array.length; i < e; ++i) {
            if (array[i] === value) {
                return true;
            }
        }
        return false;
    }
    
    function prompt(p) {
        WScript.Stdout.Write(p + " > ");
        return WScript.StdIn.ReadLine();
    }
    
    function alert(s) {
        WScript.Echo(s);
    }
    
    var possibleOptions = ["male", "female", "m", "f"];
    var gender = prompt("What's your gender?","");
    while(!arrayContains(possibleOptions, gender))
        gender = prompt("Invalid input. What's your gender?");
    var name = prompt("What's your name?","");
    var greeting = (gender == "male" || gender == "m") ? "Sup dude." : "Sup girl.";
    alert("Hello, " + name + "! " + greeting);
    

    output (console):

    cscript 26073853.js
    What's your gender? > neuter
    Invalid input. What's your gender? > male
    What's your name? > tarzan
    Hello, tarzan! Sup dude.
    
    cscript 26073853.js
    What's your gender? > female
    What's your name? > jane
    Hello, jane! Sup girl.