如何通过普通数组创建键/值数组?

时间:2015-04-22 07:51:23

标签: javascript

以下是代码和fiddle

var config = function(){
    return {
        name: ["john", "lucy", "lily"],
        age: ["22", "21", "22"],
        gender: ["male", "female", "female"],
        people: function(index){
            index--;
            this.name = name[index];
            this.age = age[index];
            this.gender = gender[index];
        },
        people2: function(index){
            index--;
            this["name"] = name[index];
            this["age"] = age[index];
            this["gender"] = gender[index];
        },
    };
}();

alert(config.people(1).name);
alert(config.people2(1).name);

我可以通过以下代码获取值:

config.name[1];

我想重构一个键/值数组,如:

{name:"john",age:22,gender:male}

索引值委托第一,第二和第三人信息。 谁能帮助我让代码工作?我被困了!

3 个答案:

答案 0 :(得分:3)

您可以返回一个对象



var config = function() {
  return {
    name: ["john", "lucy", "lily"],
    age: ["22", "21", "22"],
    gender: ["male", "female", "female"],
    people: function(index) {
      index--;
      return {
        name: this.name[index],
        age: this.age[index],
        gender: this.gender[index]
      };
    }
  };
}();

alert(config.people(1).name);




答案 1 :(得分:2)

一种可能性是,在不改变代码的情况下,如下所示:

var config = function(){
    var name = ["john", "lucy", "lily"],
        age = ["22", "21", "22"],
        gender = ["male", "female", "female"];
    return {
        people: function(index){
           return {
             name: name[index],
             age: age[index],
             gender: gender[index]
           }   
        }
    };
}();

答案 2 :(得分:0)

如果您仍想重组配置对象(粉碎数组)

    var config = function(){
    return {
        name: ["john", "lucy", "lily"],
        age: ["22", "21", "22"],
        gender: ["male", "female", "female"],
        people: function(index){
            index--;
            this.name = this.name[index];
            this.age = this.age[index];
            this.gender = this.gender[index];
        },
    };
}();

config
***Object {name: Array[3], age: Array[3], gender: Array[3], people: function}
config.people(1)
config
***Object {name: "john", age: "22", gender: "male", people: function}