将对象作为变量传递

时间:2018-08-27 19:35:54

标签: javascript arrays object

我得到了一个数组(请参见下面的数组中的一个对象)。我想通过传入的变量访问该对象。能否请您解释为什么whatType变量不起作用?

 const myfunction = (whatType) => {
    var mylist = {
        bio: null,
        email:  "user@domain.com",
        firstname: "Anna",
        id: 318,
        lastAvatar: null,
        lastMessage: null,
        lastname: "Nickson",
        nickname: "anny"
     };
      console.log (mylist.whatType)
    }

firstfunction () {
    const passthis = 'bio';
    myfunction (passthis);
};

3 个答案:

答案 0 :(得分:2)

您要将console.log (mylist.whatType)替换为console.log (mylist[whatType])

因为

mylist.bio === mylist['bio']

如果biowhatType变量上的字符串,则必须使用:

mylist[whatType]替换为mylist["bio"](与mylist.bio相同)

您的职能将是(具有更好的名字)

const getUserField = (attr) => {
    var user = {
        bio: null,
        email:  "user@domain.com",
        firstname: "Anna",
        id: 318,
        lastAvatar: null,
        lastMessage: null,
        lastname: "Nickson",
        nickname: "anny"
    }
    return user[attr]
}

firstfunction () {
    const attr = 'bio';
    console.log("User value for " + attr + ":", getUserField (attr))
}

答案 1 :(得分:0)

如果要从mylist访问whatType,则需要将其作为属性添加到mylist。

const myfunction = (whatType) => {
  var mylist = {
    bio: null,
    email: "user@domain.com",
    firstname: "Anna",
    id: 318,
    lastAvatar: null,
    lastMessage: null,
    lastname: "Nickson",
    nickname: "anny",
    whatType
  };
  console.log(mylist.whatType)
}


const passthis = 'bio';
myfunction(passthis);

如果您的目标是根据变量属性名称查询对象,则可以使用方括号:

const myfunction = (whatType) => {
  var mylist = {
    bio: null,
    email: "user@domain.com",
    firstname: "Anna",
    id: 318,
    lastAvatar: null,
    lastMessage: null,
    lastname: "Nickson",
    nickname: "anny",
    whatType
  };
  console.log(mylist[whatType])
}

const passthis = 'bio';
myfunction(passthis);

答案 2 :(得分:0)

const myfunction = (whatType) => {
var mylist = {};
    mylist[whatType] = {
        bio: null,
        email:  "user@domain.com",
        firstname: "Anna",
        id: 318,
        lastAvatar: null,
        lastMessage: null,
        lastname: "Nickson",
        nickname: "anny"
     };
      console.log (mylist[whatType])
    }

firstfunction () {
    const passthis = 'bio';
    myfunction (passthis);
};