拥有这个数组:
const xx = [
{
name: "Alex",
income: 324300,
total: 3030000
},
{
name: "Snake",
income: 3433000,
total: 34323000
},
{
name: "Wake",
income: 4,
total: 3
}
];
如果值为int(收入和总计),我想循环遍历并执行某些操作。我该怎么做呢?
这是我到目前为止所尝试的,我真的不知道如何取出对象值并测试它是否为int
for (var key in xx) {
var arr = xx[key];
for( var i = 0; i < arr.length; i++ ) {
var obj = arr[ i ];
}
}
}
答案 0 :(得分:0)
尝试:
const xx = [
{
name: "Alex",
income: 324300,
total: 3030000
},
{
name: "Snake",
income: 3433000,
total: 34323000
},
{
name: "Wake",
income: 4,
total: 3
}
];
xx.forEach(item => {
Object.keys(item).forEach(key => {
if (!isNaN(parseInt(item[key])) && isFinite(item[key])) {
// do something here
console.log('INT: ' + item[key]);
}
});
});
答案 1 :(得分:0)
您需要与外部交换内部。并使用:
typeof xx[i][k] === "number"
或xx[i][k] === +xx[i][k]
检查值是否为
一个号码。parseInt(xx[i][k]) === xx[i][k]
检查值是否为整数
号。参见示例:
const xx = [{
name: "Alex",
income: 324300,
total: 3030000
}, {
name: "Snake",
income: 34.33000,
total: 34323000
}, {
name: "Wake",
income: 4,
total: 3
}];
for (var i = 0; i < xx.length; i++) {
for (var k in xx[i]) {
//if(parseInt(xx[i][k]) === xx[i][k]) //integer
//if(typeof xx[i][k] == "number") //number
if (xx[i][k] === +xx[i][k]) { //number
console.log(k + ": " + xx[i][k]);
}
}
}