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

Angular 10中如何解决'Move this array "sort" operation to a separate statement'提示问题

Fixing "Move this array 'sort' operation to a separate statement" in Angular 10

Hey there! That linting warning you're seeing is your linter (most likely ESLint) flagging a common code style issue—specifically, it doesn't like that you're combining the array sort operation with an assignment in the same line. Let's break down why this happens and how to fix it.

Why the warning pops up

The Array.prototype.sort() method is mutating—it modifies the original array directly. When you write this.#Type.externalControls = this.#Type.externalControls.sort(sortFn);, you're essentially assigning the array back to itself after modifying it, which is redundant. Linters flag this because it can make code harder to read (hiding the side effect of sort) and goes against clean code practices that favor separating operations into distinct steps.

Solution 1: Use the in-place sort (simplest fix)

Since sort already modifies the original array, you can just run the sort operation on its own line, no assignment needed:

if (isDefined(this.#Type.externalControls)){
  // Move sort to its own separate statement
  this.#Type.externalControls.sort(sortFn);
  
  this.#Type.externalControls.forEach((control: ITypeControl) => {
    externalForm.push(new FormControl(control));
  });
}

Solution 2: Sort a copy (if you want to preserve the original array)

If you need to keep the original externalControls array unchanged, create a copy first, sort the copy, then assign it back. This also satisfies the linter's requirement for a separate statement:

if (isDefined(this.#Type.externalControls)){
  // Create a copy of the array first, then sort
  const sortedExternalControls = [...this.#Type.externalControls].sort(sortFn);
  
  // Assign the sorted copy back if needed
  this.#Type.externalControls = sortedExternalControls;
  
  sortedExternalControls.forEach((control: ITypeControl) => {
    externalForm.push(new FormControl(control));
  });
}

Both of these fixes will resolve the linting warning while making your code more explicit and easier to follow.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 16:02:49