Angular 10中如何解决'Move this array "sort" operation to a separate statement'提示问题
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

