是否有办法将for ... in循环中的所有内容过滤掉以仅获取对象?For ...在环路中仅筛选对象
我正在写一个函数来循环嵌套对象来查找某些数据片段,然后将其保存到localStorage。
实施例:
var equipped = {
data: [the rest of the properties of equipped go here],
tool: {
data: [the rest of the properties of tool go here],
axe: {
data: [the rest of the properties of axe go here],
iron: {...},
steel: {...}
}
}
}
的工具/ AX /金属属性都动态地生成的,并且每个时间是不同的。金属属性内部是我试图保存的数据。如果我试图访问数据,我通常会循环访问数据(使用knockoutjs进行绑定,仅仅对foreach数据数组更容易),但是我使用for ... in循环中的变量来构建在对其进行字符串化之前,我的localStorage对象中的其余部分树。
我如何阅读对象:
for (var type in equipped) {
if (check goes here) {
savedValue.equipped[type] = {};
for (var category in equipped[type]) {
etc etc...
}
}
}
我明白一切都是对象类型,所以我不能只是做一个instanceof
或typeof
定义的对象将它们过滤出来。是否有另一种简单的方法在if语句中执行它,还是必须从构造函数中完成树的每一步,因此我可以instanceof RealObject
?
并非一切都将复出为“对象”时调用'typeof运算'。请参阅:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof – User 2014-11-06 05:56:34
不,但数组会。我只需要做一个if(typeof type ==='object'&&!Array.isArray(type))来解决这个问题? – LastElf 2014-11-06 06:11:51