简体   繁体   中英

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. 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.

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' ]

   // 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. Currently Math.random evaluates to NaN therefore randomI is NaN too and your code 'breaks'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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