这是我第一次用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
}
}
简而言之,我复制了原始数组,对复制的数组做了大量操作,并且不想改变原始数组,但是当我同时复制和原始数组console.log时,原始数组也会改变。对此有什么明确的解释吗?
主要目标是复制原始数组,更改复制的数组,并维护原始数组。
发布于 2022-11-20 18:55:40
这是因为.slice做一个浅拷贝,而不复制嵌套对象。由于您使用的是二维数组,这是预期的。
用途:const input = JSON.parse(JSON.stringify(linsys))
浅克隆不复制嵌套对象。因此,如果一个对象包含一个对象,那么您的.slice将保留对该对象原始副本的引用,而不是创建一个副本。因此,值会发生变化。
如果是浅薄的拷贝-
Heap).
例如:
var a = [
[1, 2], // This still is referencing to the original reference
[5,7]
]
https://stackoverflow.com/questions/74513670
复制相似问题