首页 > 解决方案 > 我在使用 for in 循环删除对象键时遇到问题

问题描述

我正在使用 for x in 循环来检查一个值是否 == 到 [],如果是,则使用 remove 删除该属性,但它似乎不起作用。

const whosOnline = (a) => {

var obj = { online:[],
offline:[],
away:[] };



for(let i = 0; i < a.length; i++){
if(a[i].lastActivity > 10 && a[i].status == 'online'){obj.away.push(a[i].username)}
else if(a[i].status == 'offline'){obj.offline.push(a[i].username)}
else{obj.online.push(a[i].username)}
  }
  for(let x in obj){
  console.log(obj[x])
   if(obj[x] === []){delete obj[x]}}
  return obj
    }

标签: javascriptobjectfor-loop

解决方案


您很接近,但是您还需要为每个对象键值引用数组索引。注释在下面的代码中解释了这一点。

var obj = { online:[],
offline:[],
away:[] };

for(var x in obj){
    if(!obj[x][0]){ // The 0 is the index inside the online array, next loop it will be the offline array and then the away array.
        console.log('The array is empty');
        // Do what you want to do now that it is empty
        // This will continue to loop through and check the value of all the keys in the object.
    }
}
console.log('done');

祝你好运 - 来自 https://spangle.com.au的 Mitch


推荐阅读