【发布时间】:2022-11-21 10:55:40
【问题描述】:
这是我第一次在 TypeScript 中编写 slice() 方法。我知道 slice() 方法应该返回一个数组的副本。这是代码的一部分
class ChapterOne {
// Gauss Jordan Elimination
// Notes: Only solve system of linear equation with one solution
static gaussJordanElim( linsys : number[][] ) {
const numOfEquation = linsys.length
const numOfUnknown = linsys[0].length - 1
if (numOfUnknown > numOfEquation) return 'This System of Linear Equation either have no solution or have infinite solutions'
// I slice it here.
const input = linsys.slice()
const length = input.length
// pointer = i, row to operate = j, column to operate = k
for (let i = 0; i < length; i += 1) {
if (input[i][i] === 0) return 'Mathematical Error! Cannot divide by zero'
for (let j = 0; j < length; j += 1) {
if (i !== j) {
const ratio = input[j][i] / input[i][i]
for (let k = 0; k < length + 1; k += 1) {
input[j][k] = input[j][k] - ratio * input[i][k]
}
}
}
}
// I Checked it here
console.log(input)
console.log(linsys)
const output = input.map((row, pointer) => row[length] / row[pointer])
return output
}
}
简而言之,我制作了原始数组的副本,对复制的数组进行了大量操作,并且不想改变原始数组但是当我对复制的和原始的进行控制台记录时,原始的也发生了变化。对此有明确的解释吗?
主要目标是复制原始数组,更改复制的数组,并维护原始数组。
【问题讨论】:
-
这是因为 .slice 做的是浅拷贝,不拷贝嵌套对象。由于您使用的是二维数组,因此这是预期的。使用:
const input = JSON.parse(JSON.stringify(linsys)).slice() -
您需要创建数组及其所有子数组的深层副本。您可以使用
structuredClone算法来做到这一点。 -
^@subodhkalika 序列化和反序列化后不需要
slice。
标签: arrays typescript slice