JavaScript 对象:通过名称作为字符串访问变量属性

发布于 2024-10-03 18:53:10 字数 303 浏览 2 评论 0原文

如果我有一个如下所示的 JavaScript 对象

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

,并且有一个传递该对象和属性名称的函数,那么

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

read_prop(object, property) 的主体会是什么样子?

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');

what would the body of read_prop(object, property) look like?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

情话难免假 2024-10-10 18:53:10

您不需要它的函数 - 只需使用 括号表示法

var side = columns['right'];

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

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

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

为了回答下面一些与原始问题没有直接关系的评论,可以通过多个括号引用嵌套对象。如果您有像这样的嵌套对象:

var foo = { a: 1, b: 2, c: {x: 999, y:998, z: 997}};

您可以按如下方式访问 c 的属性 x

var cx = foo['c']['x']

如果属性未定义,则尝试引用它将返回 undefined(不是 nullfalse):

foo['c']['q'] === null
// returns false

foo['c']['q'] === false
// returns false

foo['c']['q'] === undefined
// returns true

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

var side = columns['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];
}

To answer some of the comments below that aren't directly related to the original question, nested objects can be referenced through multiple brackets. If you have a nested object like so:

var foo = { a: 1, b: 2, c: {x: 999, y:998, z: 997}};

you can access property x of c as follows:

var cx = foo['c']['x']

If a property is undefined, an attempt to reference it will return undefined (not null or false):

foo['c']['q'] === null
// returns false

foo['c']['q'] === false
// returns false

foo['c']['q'] === undefined
// returns true
噩梦成真你也成魔 2024-10-10 18:53:10

ThiefMaster 的答案是 100% 正确的,尽管我遇到了类似的问题,我需要从嵌套对象(对象内的对象)中获取属性,因此作为他的答案的替代方案,您可以创建一个递归解决方案,该解决方案将允许您定义一个命名法来获取任何属性,无论深度如何:

function fetchFromObject(obj, prop) {

    if(typeof obj === 'undefined') {
        return false;
    }

    var _index = prop.indexOf('.')
    if(_index > -1) {
        return fetchFromObject(obj[prop.substring(0, _index)], prop.substr(_index + 1));
    }

    return obj[prop];
}

对给定属性的字符串引用类似于 property1.property2

中的代码和注释 JsFiddle.

ThiefMaster's answer is 100% correct, although I came across a similar problem where I needed to fetch a property from a nested object (object within an object), so as an alternative to his answer, you can create a recursive solution that will allow you to define a nomenclature to grab any property, regardless of depth:

function fetchFromObject(obj, prop) {

    if(typeof obj === 'undefined') {
        return false;
    }

    var _index = prop.indexOf('.')
    if(_index > -1) {
        return fetchFromObject(obj[prop.substring(0, _index)], prop.substr(_index + 1));
    }

    return obj[prop];
}

Where your string reference to a given property ressembles property1.property2

Code and comments in JsFiddle.

春风十里 2024-10-10 18:53:10

由于上面的答案对我的项目有所帮助(我问了一个重复的问题并在此处引用),因此我在嵌套在 var 中时提交了一个括号表示法的答案(我的测试代码):

<html>
<head>
  <script type="text/javascript">
    function displayFile(whatOption, whatColor) {
      var Test01 = {
        rectangle: {
          red: "RectangleRedFile",
          blue: "RectangleBlueFile"
        },
        square: {
          red: "SquareRedFile",
          blue: "SquareBlueFile"
        }
      };
      var filename = Test01[whatOption][whatColor];
      alert(filename);
    }
  </script>
</head>
<body>
  <p onclick="displayFile('rectangle', 'red')">[ Rec Red ]</p>
  <br/>
  <p onclick="displayFile('square', 'blue')">[ Sq Blue ]</p>
  <br/>
  <p onclick="displayFile('square', 'red')">[ Sq Red ]</p>
</body>
</html>

Since I was helped with my project by the answer above (I asked a duplicate question and was referred here), I am submitting an answer (my test code) for bracket notation when nesting within the var:

<html>
<head>
  <script type="text/javascript">
    function displayFile(whatOption, whatColor) {
      var Test01 = {
        rectangle: {
          red: "RectangleRedFile",
          blue: "RectangleBlueFile"
        },
        square: {
          red: "SquareRedFile",
          blue: "SquareBlueFile"
        }
      };
      var filename = Test01[whatOption][whatColor];
      alert(filename);
    }
  </script>
</head>
<body>
  <p onclick="displayFile('rectangle', 'red')">[ Rec Red ]</p>
  <br/>
  <p onclick="displayFile('square', 'blue')">[ Sq Blue ]</p>
  <br/>
  <p onclick="displayFile('square', 'red')">[ Sq Red ]</p>
</body>
</html>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文