2

Let's say I have an object:

var foo = {'bar1': {'baz1':1}};

And I try to access foo['bar2']['baz2']. If I was just trying to access foo['bar2'], JS would return undefined. But because I'm trying to get the next property after the undefined bar2, JS throws TypeError: Cannot read property 'baz2' of undefined.

Is there some automatic accessor for an object that first checks if baz2 exists in foo before trying to call its properties? I know I could use a try/catch block or an if statement, but I was hoping for a function along the lines of C++'s array::at, that would check for me.

4

4 回答 4

2

请记住,这仅适用于对象,例如您展示的对象,而不适用于数组(即 [0, 1, 2]),但我最喜欢的是这个:

if ('bar1' in foo)

这甚至对 HTML5 特征检测很有用。

if ('localStorage' in window)

我也可以给你一个数组,但我觉得更合乎逻辑的事情是将它的长度与给定的索引进行比较。并且...不要将未定义的值插入数组。你知道的。=p

于 2013-07-16T17:06:16.627 回答
2

你可以很容易地编写自己的:

function at(obj, property) {
  var props = property.split('.');
  for(var i = 0; i < props.length; i++) {
    if (typeof obj === 'undefined') {
      return;
    }
    obj = obj[props[i]];
  }
  return obj;
}

var foo = {'bar1': {'baz1':1}};
console.log(at(foo, 'bar1.baz1'));
// => 1
console.log(at(foo, 'bar2.baz2'));
// => undefined
于 2013-07-16T17:12:06.737 回答
1

您可以使用in运算符:

if("bar2" in foo) {
   //do stuff with foo['bar2']
}

或者您可以检查是否foo['bar2']undefined

if(typeof foo['bar2'] !== "undefined") {
    //do stuff with foo['bar2']
}

此外,您使用的是对象而不是数组(嗯,它们是关联数组,但也是 JavaScript 中的对象)。

于 2013-07-16T17:05:12.237 回答
0

foo['bar2'] && foo['bar2']['baz2']也会成功的。

于 2013-07-16T17:14:57.217 回答