如何检查对象中的对象是否存在

发布于 2024-11-18 05:05:20 字数 314 浏览 4 评论 0原文

似乎以下用于检查对象成员是否存在的技术会产生错误,因为在检查之前尚未声明“bar”父对象,这意味着我要么必须在检查之前声明它,要么使用两个“typeof”表达式,其中任何一个都是多余的代码:

var foo = {},
    newVal = (typeof foo.bar.myVal !== 'undefined' ? foo.bar.myVal : null );

Error: foo.bar is undefined

那么,如何检查未声明对象中的成员是否存在而不产生错误?

我喜欢 JavaScript,但有时...

It seems that the following technique for checking the existence of an object member produces an error because the 'bar' parent object hasn't been declared before the check, which means I either have to declare it before the check or use two 'typeof' expressions, either of which would be excess code:

var foo = {},
    newVal = (typeof foo.bar.myVal !== 'undefined' ? foo.bar.myVal : null );

Error: foo.bar is undefined

So, how do you check if a member within an undeclared object exists without producing an error?

I love javascript, but sometimes...

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

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

发布评论

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

评论(6

思念满溢 2024-11-25 05:05:21

只需使用下面的代码即可完成:

var newVal = (foo && foo.bar && typeof foo.bar.myVal !== 'undefined') ? foo.bar.myVal : foo.bar.myVal

属性为 null 或未定义,它将被评估为 false,因此上面的代码只会处理第一个“false”语句。

It can be done simply using the code below:

var newVal = (foo && foo.bar && typeof foo.bar.myVal !== 'undefined') ? foo.bar.myVal : foo.bar.myVal

A property is null or undefined, it will be evaluated as false so the above code will only process up to the first 'false' statement.

梦忆晨望 2024-11-25 05:05:21
var newVal = ('foo' in window && // could be typeof foo !== 'undefined' if you want all scopes
             'bar' in foo &&
             'myVal' in foo.bar) ? foo.bar.myVal : null;

公平地说,JavaScript 读起来几乎就像自然语言一样。

var newVal = ('foo' in window && // could be typeof foo !== 'undefined' if you want all scopes
             'bar' in foo &&
             'myVal' in foo.bar) ? foo.bar.myVal : null;

To be fair to javascript, that reads almost like natural language.

深爱不及久伴 2024-11-25 05:05:21

最简单的测试是:

if (foo && foo.bar) {
  // play with foo.bar.myVal  ... 
}

The simplest test is:

if (foo && foo.bar) {
  // play with foo.bar.myVal  ... 
}
绿光 2024-11-25 05:05:21

您可以将其包装到一个方法中:

function checkGraph(obj, graphPath)
{
  var parts = graphPath.split(".");
  var root = obj;

  for (var i = 0; i < parts.length; i++)
  {
    var part = parts[i];
    if (root[part] && root.hasOwnProperty(part))
      root = root[part];
    else
      return false;
  }

  return true;
}

您可以将其称为:

var foo = {},
    newVal = checkGraph(foo, "bar.myVal") ? foo.bar.myVal : null;

You could wrap it up into a method:

function checkGraph(obj, graphPath)
{
  var parts = graphPath.split(".");
  var root = obj;

  for (var i = 0; i < parts.length; i++)
  {
    var part = parts[i];
    if (root[part] && root.hasOwnProperty(part))
      root = root[part];
    else
      return false;
  }

  return true;
}

Where you could call it as:

var foo = {},
    newVal = checkGraph(foo, "bar.myVal") ? foo.bar.myVal : null;
花期渐远 2024-11-25 05:05:21

正如 Matthew Abbott 在他的回复中给出的那样,如果你做了很多事情,你可以编写一个方法供以后使用它深入研究子属性,其中整个对象或链上的某个位置可以为空。下面是我使用 lodash 的实现。

checkGraph(obj, graphPath) {
    if (obj) {
      let root = obj;
      _.each(graphPath.split('.'), part => {
        if (root[part]) {
          root = root[part];
        } else {
          return false; // bad property
        }
      });
      return true;
    }
    return false; // bad object
  }

您可以像这样调用该方法:

if (this.checkGraph(object, 'property.subproperty') {
    // do thing
}

As Matthew Abbott gave in his response, you can write a method for it to use it later if you do a lot of diving into child properties where the whole object or somewhere along the chain can be null. Below is my implementation using lodash.

checkGraph(obj, graphPath) {
    if (obj) {
      let root = obj;
      _.each(graphPath.split('.'), part => {
        if (root[part]) {
          root = root[part];
        } else {
          return false; // bad property
        }
      });
      return true;
    }
    return false; // bad object
  }

You can call the method like this:

if (this.checkGraph(object, 'property.subproperty') {
    // do thing
}
始终不够爱げ你 2024-11-25 05:05:21

还有另一种方法是使用 JS 转译器,例如 Babel

if (foo?.bar) {
  // play with foo.bar.myVal  ... 
}

There is another way is you use a JS transpiler like Babel:

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