如何在不使用if或case swtich的情况下访问对象[javascript]

时间:2018-08-12 20:24:06

标签: javascript object javascript-objects

所以我创建了一个这样的对象原型:

function myObjProto(one, two, three) {
    this.one = one;
    this.two = two;
    this.three = three;  };

然后创建了一堆这样的对象:

let myObj1 = new myObjProto (
    /* one */ "one", 
    /* two */ "two", 
    /* three */ "three" );
let myObj2 = new myObjProto (
    /* one */ "one", 
    /* two */ "two", 
    /* three */ "three" );

我有一个正在更改的变量(myObj1,myObj2等),我知道一种访问值的方法是说

let myVar = "myObj";

let var1;
let var2;
let var3;

if (myVar == myObj1){
    var1 = myObj1.one;
    var2 = myObj1.two;
    var3 = myObj1.three;
}
else {
    var1 = myObj2.one;
    var2 = myObj2.two;
    var3 = myObj3.three;
}

但是必须有更好的方法。我有7个物件!

我尝试过这样的事情:

var1 = myVar.one;
var2 = myVar.two;
var3 = myVar.three;

但是我得到的只是“未定义”。请帮忙。

(完整示例为here on JSbin

2 个答案:

答案 0 :(得分:3)

您可以使用所有类型的对象,并使用方括号将类型设为property accessor

var Dwarf = new race(),
    Elf = new race(),
    Gnome = new race(),
    HalfElf = new race(),
    HalfOrc = new race(),
    Halfling = new race(),
    Human = new race(),
    types = { Dwarf, Elf, Gnome, HalfElf, HalfOrc, Halfling, Human },
    type = 'Halfling';


// access:
types[type].language

答案 1 :(得分:-1)

您可以使用对象解构,但是变量必须匹配

const {one, two, three} = myVar == myObj1 ? myObj1 : myObj2;

现在,一,二,三将是正确对象的值