JavaScript对象:按名称访问变量属性为字符串 [英] JavaScript object: access variable property by name as string

查看:97
本文介绍了JavaScript对象:按名称访问变量属性为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个类似于下面的javascript对象

If I have a javascript object that looks like below

var columns = {
  left: true,
  center : false,
  right : false
}

和我有一个传递对象的函数,以及像这样的属性名称

and I have a function that is passed both the object, and a property name like so

//should return false
var side = read_prop(columns, 'right');

read_prop(object,property)的主体是什么看起来像?

推荐答案

你不需要它的功能 - 只需使用 括号表示法

You don't need a function for it - simply use the bracket notation:

var side = columns['right'];

这等于 点符号 var side = columns.right; ,当使用括号表示法时, right 也可能来自变量,函数返回值等。

This is equal to dot notation, var side = columns.right;, except the fact that right could also come from a variable, function return value, etc., when using bracket notation.

如果你需要一个函数,这里是:

If you NEED a function for it, here it is:

function read_prop(obj, prop) {
    return obj[prop];
}

这篇关于JavaScript对象:按名称访问变量属性为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆