由于某些原因,我无法按照预期的方式运行下面的代码。
我用随机的15个元素声明了可变的dna,每个元素都是来自数组dnaBases的随机字母。
突变函数应该用随机的15个元素创建新的(类似的数组),但是第一个数组中的元素不能重复。相反,应该将它们替换为dnaBases数组中的其余三个元素。
在我的代码中的问题是,有时字母重复,即使在以前的情况下,没有。
const dnaBases = ['A', 'T', 'C', 'G']
var dna = []
for (let i = 0; i < 15; i++) {
dna.push(dnaBases[Math.floor(Math.random() * 4)])
}
function mutate() {
console.log(dna) // to check newly generated dna array
var tmp = []
var newDnaBases = ['A', 'T', 'C', 'G']
for (var j = 0; j < 15; j++) {
tmp.push(newDnaBases[Math.floor(Math.random() * 4)]);
}
console.log(tmp) // to check newly generated tmp array
for (var k = 0; k < tmp.length; k++) {
var randomIndex = Math.floor(Math.random() * 3);
if (tmp[k] === dna[k]) {
var x = newDnaBases.splice(tmp[k], 1);
tmp[k] = newDnaBases[randomIndex];
newDnaBases.push(x.toString());
}
}
console.log(tmp) // to see how tmp has changed after for loop
console.log(newDnaBases) // to check if newDnaBases is not corrupted
}
mutate()我是Javascript的新手,乍一看我看不出这个问题。
非常感谢!
发布于 2019-12-09 14:31:32
在js中,使用split、片ou还原之类的数组方法来返回数组变量的“克隆”,并对该方法进行更改。喜欢
a = [1,2,3]
b = a.filter(i => {
if (i === 2) {
return true
} else {
return false
}
})
b[0] === 2 // true
a[2] === 3 // true所以在你的代码中:
const dnaBases = ['A', 'T', 'C', 'G']
var dna = []
for (let i = 0; i < 15; i++) {
dna.push(dnaBases[Math.floor(Math.random() * 4)])
}
function mutate() {
console.log(dna)
var tmp = []
var newDnaBases = ['A', 'T', 'C', 'G']
for (var j = 0; j < 15; j++) {
tmp.push(newDnaBases[Math.floor(Math.random() * 4)]);
}
console.log(tmp) // to check newly generated tmp array
for (var k = 0; k < tmp.length; k++) {
var randomIndex = Math.floor(Math.random() * 3);
if (tmp[k] === dna[k]) {
var x = newDnaBases.filter(i=> i!== tmp[k]) //returns the array without the repeated item, without altering the original variable
tmp[k] = x[Math.floor(Math.random() * 2)];
}
}
console.log(tmp)
console.log(newDnaBases)
}
mutate()https://stackoverflow.com/questions/59250818
复制相似问题