Javascript question here. I'm currently working on a codecademy project involving a factory function, and am writing methods that are supposed to access the properties of the given object.
My first method works just fine, and makes use of the this. notation, but for some reason my second one is giving me real trouble. After checking, it keeps returning undefined. Specifically, the mutate() method works just fine, but the compareDNA() function is the problem.
I can't see that I'm doing anything different between them.
Here's the error:
if (this.dna[i] === object.dna[i]) {
^
TypeError: Cannot read property '0' of undefined
Even with the return keyword I still am getting undefined. Here's the code:
// 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 = (number, array) => {
return {
specimenNum: number,
dna: array,
mutate() {
let randomIndex = Math.floor(Math.random() * array.length);
const randBase = returnRandBase();
while (this.dna[randomIndex] === randBase) {
this.dna[randomIndex] = returnRandBase();
}
return this.dna;
},
compareDNA: (object) => {
let counter = 0;
for (let i=0; i<15; i++) {
if (this.dna[i] === object.dna[i]) {
counter++;
}
}
let percentage = (counter/15)*100;
return `Specimen #${this.specimenNum} and Specimen #${object.specimenNum} share %${percentage} DNA in common.`
}
}
}
const example1 = pAequorFactory(1, mockUpStrand());
const example2 = pAequorFactory(2, mockUpStrand());
console.log(example2.dna);
example2.mutate();
console.log(example2.dna);
example1.compareDNA(example2);