嘿,基本上我想知道是否可以将对象的属性作为切换案例中的条件。这样的事情。
function Person (age,name){
this.age = age
this.name = name
}
var person1 = new Person(22,"Ken")
var person2 = new Person(42,"Ben")
var person3 = new Person(62,"Len")
switch(the attribute here lets say it was age for example){
case person1: Do something; Basically age for person1 do this age for person 2 do this etc.
break;
case person2: Do something;
break;
case person3: Do something;
break;
}
很抱歉,如果不清楚我是javascript的新手,我想知道这种事情是可能的。
答案 0 :(得分:0)
我认为你要做的是:
function Person (age,name){
this.age = age;
this.name = name;
}
var person1 = new Person(22,"Ken");
var person2 = new Person(42,"Ben");
var person3 = new Person(62,"Len");
switch(person.age){
case 22:
alert("the person is " + person.name);
break;
case 42:
//do something here;
break;
default:
//do something default;
break;
}
你确定可以将一个对象的属性放入switch / case条件中,因为它就像其他变量一样,为什么不呢。
答案 1 :(得分:0)
尝试:
switch(this.age){
case x:
}
this
表示父对象。所以如果我说this.age它代表父对象的年龄,而不需要指定年龄。
答案 2 :(得分:0)
另外,你可以这样做:
function Person(age, name) {
this.age = age;
this.name = name;
}
var person1 = new Person(22, "Ken");
var person2 = new Person(42, "Ben");
var person3 = new Person(62, "Len");
var person, people = [person1, person2, person3];
while (p = people.shift()) {
console.log("Q: Do you think " + p.name + " is old?");
console.log("A: " + isOld(p));
}
function isOld(person) {
switch(true) {
case person.age < 40:
return "Not at all.";
case person.age < 60:
return "I prefer not to comment.";
default:
return "Who? The grandpa?";
}
}