gpt4 book ai didi

javascript - 尝试更改对象属性内的数组值

转载 作者:行者123 更新时间:2023-11-28 16:54:28 25 4
gpt4 key购买 nike

我正在做一个项目,我需要在存储在对象属性内的数组中选择一个随机元素,然后使用方法将其更改为其他元素。这是该项目的步骤:

.mutate() is responsible for randomly selecting a base in the object’s dna property and changing the current base to a different base. Then .mutate() will return the object’s dna.

For example, if the randomly selected base is the 1st base and it is 'A', the base must be changed to 'T', 'C', or 'G'. But it cannot be 'A' again.

当我尝试这样做时,我的输出总是这样结束:第一个数组是原始数组['C'、'T'、'A'、'A'、'G'、'A'、'G'、'G'、'C'、'G'、'T'、'A'、' A'、'T'、'G'][ 'C', 'T', 'A', 'A', 'G', 'A', 'G', 'G', 'C', 'G', 'T', 'A', 'A', 'T', 'G', NaN:'G']

   // 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
}

const pAequorFactory= (num, strand) =>{
return {
specimenNum: num,
dna: strand,
mutate(){
const randomI = Math.floor(Math.random * this.dna.length);
let dnaBase = this.dna[randomI];
const randomBase = returnRandBase()
if(dnaBase !== randomBase){
this.dna[randomI] = randomBase
} else {
this.mutate()
}
return this.dna
}
}
}

const specimen1 = pAequorFactory(1,[ 'C', 'T', 'A', 'A', 'G', 'A', 'G', 'G', 'C', 'G', 'T', 'A', 'A', 'T', 'G' ]);

console.log(specimen1.dna)
console.log(specimen1.mutate())

最佳答案

改变

const randomI = Math.floor(Math.random * this.dna.length);

const randomI = Math.floor(Math.random() * this.dna.length);

.random() 是一个方法,需要 () 来调用它。目前,Math.random 的计算结果为 NaN,因此 randomI 也是 NaN,并且您的代码“中断”

关于javascript - 尝试更改对象属性内的数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59470560/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com