【问题标题】:I have an issue with removing an object key with a for in loop我在使用 for in 循环删除对象键时遇到问题
【发布时间】:2018-12-05 22:05:39
【问题描述】:

我正在使用 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
    }

【问题讨论】:

  • 您正在比较不同的对象,即使它们都是空数组。尝试检查数组是否为空。

标签: javascript object for-loop


【解决方案1】:

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

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

【讨论】:

  • 非常感谢伙计们,我完全是个笨蛋。这很奇怪,因为如果我调用 object[x] 我会得到 [] 所以我想如果我使用 if 语句达到同样的效果,它会返回 true。但现在我知道我还必须引用数组索引。
【解决方案2】:

使用一些调试(例如,简单地测试是否打印了 console.log),您会发现您的 if 条件永远不会为真。

这是因为您测试一个数组是否等于一个新创建的空数组。永远不会出现这种情况,因为对象是通过对象引用而不是值来比较的。

相反,您可能希望通过执行 'if(obj[x].length===0)' (或更短:'if(!obj[x].length)')来测试您的数组是否为空

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 2019-09-06
    • 2019-02-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多