繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM