多次访问javascript数组
我有一个简单的函数,其中我从表单中传递了一个name和age参数。我调用了一个外部方法来生成“isReady”结果,但是当我运行这个方法时,“isReady”结果打印的是代码,而不是期望的结果。这很简单,我不知道我遗漏了什么多次访问javascript数组,javascript,function,Javascript,Function,我有一个简单的函数,其中我从表单中传递了一个name和age参数。我调用了一个外部方法来生成“isReady”结果,但是当我运行这个方法时,“isReady”结果打印的是代码,而不是期望的结果。这很简单,我不知道我遗漏了什么 function getWho(name, age) { this.name = name; this.age = age; this.isReady = youngOrOld; return [this.name, this.age,
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;
}
函数getWho(姓名、年龄){
this.name=名称;
这个。年龄=年龄;
this.isReady=youngOrOld;
返回[this.name,this.age,this.isReady];
}
函数youngOrOld(){
var结果;
var yourAge=这个年龄;
开关(你的年龄){
病例(年龄<13岁):
result=“你只是个宝贝”;
打破
案例(yourAge>=13岁和&yourAge<18岁):
result=“你才十几岁”;
打破
案例(yourAge>=18岁和&yourAge<50岁):
结果=“您是成年人”;
打破
案例(您的年龄>=50):
result=“您是一名大四学生”;
打破
违约:
结果=”;
}
返回结果;
}
函数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=“你好”+myName+”,您是“+myAge+”老的“+myResult;
}
结果如下:
你好,克里斯,你23岁了,函数youngOrOld(){var result;var yourAge=this.age;switch(yourAge){case(yourAge<13):result=“你只是个宝贝”break;case(yourAge>=13&&yourAge<18):result=“你十几岁”break;case(yourAge>=18&&yourAge<50):result=“你是成年人”break;case(yourAge>=50):result=“You are a senior”break;default:result=“;}返回结果;}这是因为youngOrOld是一个函数,当它被添加到字符串中时,解释器调用返回整个函数代码的字符串方法。必须执行函数才能得到结果 这是正确的代码:
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()];
}
执行这个函数怎么样
this.isReady=youngOrOld()
?