JS文件不起作用

时间:2014-09-27 10:48:13

标签: jscript

这是我的JS文件中的代码:

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);

我得到的错误:

Line: 5
char: 1
Object expected.

我无法弄清楚。

1 个答案:

答案 0 :(得分:1)

两个问题:

  1. 如评论中所述,w / cscript.exe脚本主机既不支持prompt()也不支持alert()
  2. JScript数组没有.IndexOf()方法
  3. 你必须自己动手:

    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);
    

    输出(控制台):

    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.