json 循环在比较2个数组时始终返回0

nxowjjhe  于 2023-02-14  发布在  其他
关注(0)|答案(1)|浏览(97)

我的代码应该返回两个数组之间相似性的百分比,但它总是返回0。我错过了什么?我想比较原始数组和变异数组

const returnRandBase = () => {
    const dnaBases = ['A', 'T', 'C', 'G']
    return dnaBases[Math.floor(Math.random() * 4)] 
  }
  
  // Returns a random single strand of DNA containing 15 bases
  const mockUpStrand = () => {
    const newStrand = []
    for (let i = 0; i < 15; i++) {
      newStrand.push(returnRandBase())
    }
    return newStrand
  }

const pAequorFactory = (num, arr) => {
  return {
    specimen: num,
    dna: arr,

    mutate() {
        let ranNum = Math.floor(Math.random() * this.dna.length)
          let newBase = returnRandBase()
          while (this.dna[ranNum] === newBase) {
            newBase = returnRandBase();
            }
            this.dna[ranNum] = newBase
            return this.dna
    },
    compareDNA(pAequor) {
      let matches = 0;
      let length = this.dna.length
        for (let i = 0; i< pAequor.length; i++) {
          if (length[i] === pAequor[i]){
            matches++
          }
        }  const simliaritys = matches / length * 100
          console.log(simliaritys.toFixed(2) + "%")
    } 
  }
}

const test1 = pAequorFactory(1, mockUpStrand())
console.log(test1)
const test2 = test1.mutate()
console.log(test1.dna);
(test1.compareDNA(test2))
zzlelutf

zzlelutf1#

您在mutate()中将test1的DNA值更改为this.dna[randNum] = newBase,因此mutate()返回等于test2的test1.dna。

相关问题