![](/img/trans.png)
[英]Change the state value of the property of a particular object that is inside an array
[英]Trying to change array value inside object property
我正在做一個項目,我需要在存儲在對象屬性中的數組中選擇一個隨機元素,然后使用方法將其更改為其他內容。 這是項目的步驟:
.mutate() 負責在對象的 dna 屬性中隨機選擇一個鹼基並將當前鹼基更改為不同的鹼基。 然后 .mutate() 將返回對象的 dna。
例如,如果隨機選擇的鹼基是第 1 個鹼基並且是“A”,則必須將鹼基更改為“T”、“C”或“G”。 但它不能再是'A'。
當我嘗試這樣做時,我的輸出總是這樣結束:第一個數組是原始數組 ['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
並且您的代碼“中斷”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.