您好我有关注对象:
arguments = {
familyName: undefined,
givenName: undefined,
age: undefined
};
我想循环每个并用每个键做一些事情:值。我试过这样的话:
this.arguments.forEach((item:any) => {
if(item == undefined) {
alert("Hallo");
}
});
是否可以像这样循环?我赢了正常for
或者我没有搜索这样的解决方案,我的问题是,是否可以像我上面的forEach()
那样循环播放它,如果它&#39 ; s可能如何做到这一点。我经常在数组中使用它并且它有效,所以我想也许在这样的对象中它也是可能的。
由于
答案 0 :(得分:3)
您可以通过Object.keys
循环获取密钥。
args = {
familyName: undefined,
givenName: undefined,
age: undefined
};
Object.keys(args).forEach((key/*:string*/) => {
if(args[key] === undefined) {
console.log("Hallo");
}
});
答案 1 :(得分:2)
当你在一个对象上循环时,forEach只适用于数组。
试试这个:
Object.keys(this.arguments).forEach((idx) => {
var row = this.arguments[idx];
if (row === undefined) alert('hallo');
});
你确实需要使用es6。
好的方法:
for(idx in this.arguments)
{
if (! this.arguments.hasOwnProperty(idx)) continue;
if (this.arguments[idx] === undefined) alert('hallo');
}
答案 2 :(得分:2)
没有内置函数可以帮助您迭代对象,但是,实现它们非常容易:
Object.prototype.forEach = function(callback, context = null) {
Object.keys(this).forEach((key, index, keys) => {
if(!this.hasOwnProperty(key)) {
return;
}
callback.call(context, key, this[key], index, keys);
});
return this;
}
let foo = { baz: 1, pippo: 2 };
foo.forEach((key, value, index) => console.log(index, key, value));