首页 > 解决方案 > 尝试更改对象属性内的数组值

问题描述

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

.mutate() 负责在对象的 dna 属性中随机选择一个碱基,并将当前碱基更改为不同的碱基。然后 .mutate() 将返回对象的 dna。

例如,如果随机选择的碱基是第一个碱基并且是“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())

标签: javascript

解决方案


改变

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

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

.random()是一个方法,你需要()调用它。目前Math.random评估结果也是如此,NaN并且您的代码“中断”randomINaN


推荐阅读