简体   繁体   English

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

[英]Trying to change array value inside object property

Im doing a project where i need to select a random element inside an array which is stored inside an objects property, then change it to something else with a method.我正在做一个项目,我需要在存储在对象属性中的数组中选择一个随机元素,然后使用方法将其更改为其他内容。 here is the step of the project:这是项目的步骤:

.mutate() is responsible for randomly selecting a base in the object's dna property and changing the current base to a different base. .mutate() 负责在对象的 dna 属性中随机选择一个碱基并将当前碱基更改为不同的碱基。 Then .mutate() will return the object's dna.然后 .mutate() 将返回对象的 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'.例如,如果随机选择的碱基是第 1 个碱基并且是“A”,则必须将碱​​基更改为“T”、“C”或“G”。 But it cannot be 'A' again.但它不能再是'A'。

when i attempt this my output always ends up like this: the first array is the original array [ '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' ]当我尝试这样做时,我的输出总是这样结束:第一个数组是原始数组 ['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())

Change改变

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

to

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

.random() is a method, you need () to call it. .random()是一个方法,你需要()来调用它。 Currently Math.random evaluates to NaN therefore randomI is NaN too and your code 'breaks'目前Math.random评估为NaN因此randomI也是NaN并且您的代码“中断”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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