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

使用Lodash forEach设置数组对象布尔属性仅首个对象生效问题

问题:Lodash _.forEach 在Angular中仅修改第一个数组对象属性?

我在Angular项目里尝试用Lodash的_.forEach给数组每个对象的used布尔属性设为false,但运行后只有第一个对象的used变成了false,剩下的还是true。用_.map或者原生forEach就能正常批量修改。

代码示例

import { Component, OnInit } from "@angular/core";
import * as _ from "lodash";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  title = "CodeSandbox";

  colors: {hex: string, used: boolean}[] = [
    {hex: "#ff0000", used: true},
    {hex: "#00ff00", used: true},
    {hex: "#0000ff", used: true}
  ]

  ngOnInit() {
    _.forEach(this.colors, c => c.used = false);
    console.log(this.colors);
  }
}

运行输出

0: Object
hex: "#ff0000"
used: false
1: Object
hex: "#00ff00"
used: true
2: Object
hex: "#0000ff"
used: true

原因及解决方案

问题出在_.forEach的回调返回值逻辑上:Lodash的_.forEach规定,当回调函数返回false时会立即终止遍历。你用的箭头函数c => c.used = false是单表达式写法,它的返回值就是赋值操作的结果false,所以第一次循环执行后就停止了,后续元素没有被处理。

解决方法很简单,把回调改成块级语句,避免返回false:

_.forEach(this.colors, c => { 
  c.used = false; 
});

这样块级语句默认返回undefined,不会触发_.forEach的终止逻辑,就能正常遍历所有数组元素并修改属性了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 17:02:19