javascript - 我在使用 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
}
解决方案
您很接近,但是您还需要为每个对象键值引用数组索引。注释在下面的代码中解释了这一点。
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
推荐阅读
- angular - 在 Nativescript webview 上本地服务时 index.html 的 Webpack 捆绑位置
- git - 吉特;机器重建后如何重新同步回购?
- optaplanner - 如何在模式条目中输入值
- vba - 使用单元格值进行 VBA 舍入
- reactjs - 在 JSX 中使用 FontAwesome 的 unicode 时的问题
- ios - AVAudioPlayerNode playAt() 不同步
- powerbi - Power BI Query Error: The column either doesn't exist or doesn't have a relationship to any table available in the current context
- python - popen streamlink 的列表格式
- php - phpmyadmin 不适用于 ubuntu 14.04
- php - 无法将 reCaptcha 集成到使用 AJAX 提交的 PHP 联系表单中