我有一个简单的函数,我从表单中传递名称和年龄参数。我调用外部方法来生成" isReady"结果,但是当我运行它时," isReady"结果打印代码而不是所需的结果。这很简单,我不知道我错过了什么。
function getWho(name, age) {
this.name = name;
this.age = age;
this.isReady = youngOrOld;
return [this.name, this.age, this.isReady];
}
function youngOrOld() {
var result;
var yourAge = this.age;
switch(yourAge) {
case (yourAge < 13) :
result = "You're just a babe";
break;
case (yourAge >= 13 && yourAge < 18):
result = "You're in your teens";
break;
case (yourAge >= 18 && yourAge < 50):
result = "You are an adult";
break;
case (yourAge >= 50):
result = "You are a senior";
break;
default:
result = "";
}
return result;
}
function getAgeResult(n, a) {
var myArr = getWho(n, a);
var myName = myArr[0].valueOf();
var myAge = myArr[1].valueOf();
var myResult = myArr[2].valueOf();
document.getElementById("myDiv2").innerHTML = "Hello " + myName + ", you are " + myAge + " old and " + myResult;
}
结果如下: 你好克里斯,你是23岁并且函数youngOrOld(){var result; var yourAge = this.age; switch(yourAge){case(yourAge&lt; 13):result =&#34;你只是一个宝贝&#34 ;;打破; case(yourAge&gt; = 13&amp;&amp; yourAge&lt; 18):result =&#34;你已经十几岁了?#34 ;;打破; case(yourAge&gt; = 18&amp;&amp; yourAge&lt; 50):result =&#34;你是一个成年人&#34 ;;打破; case(yourAge&gt; = 50):result =&#34;你是大四学生&#34 ;;打破;默认值:result =&#34;&#34 ;;返回结果; }
答案 0 :(得分:1)
因为youngOrOld是一个函数,当它被添加到字符串时,解释器调用toString方法返回整个函数代码。你必须执行功能才能获得结果。
这是更正后的代码:
function getWho(name, age) {
this.name = name;
this.age = age;
this.isReady = youngOrOld;
//if you execute it now youngOrOld will not recognize this.age
return [this.name, this.age, this.isReady()];
}