该计划的目的是随机创建15个DNA碱基的序列,然后能够根据要求更改此序列。这就是为什么您会发现2个有关随机DNA生成的功能,然后是带有变异方法的功能的原因。
不幸的是,console.log(dnaFactoried.mutate())
一次返回undefined
,范围为6。
这是我的代码:
// Returns a random DNA base
const returnRandBase = () => {
const dnaBases = ['A', 'T', 'C', 'G']
return dnaBases[Math.floor(Math.random() * 4)]
}
// Returns a random single stand of DNA containing 15 bases
const mockUpStrand = () => {
const newStrand = []
for (let i = 0; i < 15; i++) {
newStrand.push(returnRandBase())
}
return newStrand
}
// functionality of creation or mutation of the dna
const pAequorFactory = (number, dnaBase) => {
return {
specimenNum: number,
dna: dnaBase(),
mutate: function () {
const random = Math.floor(Math.random()* this.dna.length);
const toBeMutated = this.dna[random];
const thatMutates = returnRandBase();
if (toBeMutated == thatMutates) {
this.mutate();
} else {
this.dna.splice(random, 1, thatMutates);
return this.dna;
}
}
}
}
const dnaFactoried = pAequorFactory(1, mockUpStrand);
console.log(dnaFactoried.dna);
console.log(dnaFactoried.mutate());
答案 0 :(得分:0)
您忘记在return this.mutate()
上
if (toBeMutated == thatMutates) {
return this.mutate();
}
否则,它仅返回undefined
// Returns a random DNA base
const returnRandBase = () => {
const dnaBases = ['A', 'T', 'C', 'G']
return dnaBases[Math.floor(Math.random() * 4)]
}
// Returns a random single stand of DNA containing 15 bases
const mockUpStrand = () => {
const newStrand = []
for (let i = 0; i < 15; i++) {
newStrand.push(returnRandBase())
}
return newStrand
}
// functionality of creation or mutation of the dna
const pAequorFactory = (number, dnaBase) => {
return {
specimenNum: number,
dna: dnaBase(),
mutate: function () {
const random = Math.floor(Math.random()* this.dna.length);
const toBeMutated = this.dna[random];
const thatMutates = returnRandBase();
if (toBeMutated == thatMutates) {
return this.mutate();
} else {
this.dna.splice(random, 1, thatMutates);
return this.dna;
}
}
}
}
const dnaFactoried = pAequorFactory(1, mockUpStrand);
console.log(dnaFactoried.dna);
console.log(dnaFactoried.mutate());
答案 1 :(得分:0)
只需将return this.dna;
移至if ... else语句之外。