You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何提取JavaScript对象属性到变量并判断指定counter值是否符合条件

实现方法

你可以用JS数组内置的every()方法实现需求,该方法会遍历数组所有元素,只有所有元素都满足定义的判断条件时才返回true,否则返回false,刚好匹配你的需求。

完整代码示例

// 目标Stats对象
const Stats = {
  "life": {
    "progress": 18,
    "counter": 1
  },
  "anxiety": {
    "progress": 24.5,
    "counter": 2
  },
  "mood": {
    "progress": null,
    "counter": 0
  },
  "cognition": {
    "progress": null,
    "counter": 0
  }
}

// 定义需要校验的属性列表
const checkKeys = ['anxiety', 'mood', 'cognition']
// 执行判断
const isAllValid = checkKeys.every(key => Stats[key]?.counter > 0)
console.log(isAllValid) // 原示例输出false

// 测试满足条件的场景
Stats.mood.counter = 1
Stats.cognition.counter = 1
const isAllValid2 = checkKeys.every(key => Stats[key]?.counter > 0)
console.log(isAllValid2) // 更新后输出true

逻辑说明

  • 首先把需要校验的三个属性名存入数组checkKeys,避免硬编码冗余
  • every()方法遍历每个属性名,依次取Stats对应属性下的counter值判断是否大于0
  • 代码中加了可选链操作符?.,避免某属性不存在时报错,兼容边界场景

可选:传统for循环实现(兼容旧环境)

如果你的运行环境不支持ES6的every和可选链,可以用基础for循环实现:

function checkAllCounter() {
  const checkKeys = ['anxiety', 'mood', 'cognition']
  for(let i = 0; i < checkKeys.length; i++) {
    const key = checkKeys[i]
    // 先判断属性是否存在,再取counter校验
    if(!Stats[key] || Stats[key].counter <= 0) {
      return false
    }
  }
  return true
}
console.log(checkAllCounter())

内容的提问来源于stack exchange,提问作者guitarman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 09:15:03