我创建了一个创建对象的函数,我希望从该函数创建的对象具有唯一的键。我怎样才能做到这一点?

问题描述 投票:0回答:2

pAequorFactory()
中,调用该函数创建对象时。我希望
.specimenNum
对于所有对象都是唯一的。检查下面的代码

const pAequorFactory = (specimenNum, dna) => {
  return {
    specimenNum,
    dna,

    mutate() {
      randomBaseIndex = Math.floor[Math.random * 15];
      mutatedBase = returnRandBase();
      if (this.dna[randomBaseIndex] !== mutatedBase) {
        this.dna[randomBaseIndex] === mutatedBase;
        return this.dna;
      } else {
        mutate();
      }
    },

    compareDNA(object) {
      for (i = 0; i < 15; i++) {
        let j = 0;
        if (object.dna[i] === this.dna[i]) {
          j++;
        }
        let commonPercentage = (j / 15) * 100;
      }
      return `specimen #${this.specimenNum} and specimen #${object.specimenNum} have ${commonPercentage}% DNA in common`;
    },

    willLikelySurvive() {
      for (i = 0; i < 15; i++) {
        let j = 0;
        if (this.dna[i] === "C" || this.dna[i] === "G") {
          j++;
        }
        let survivePercentage = (j / 15) * 100;
      }
      return survivePercentage >= 60;
    },
  };
};

我还没有尝试过任何东西,但我正在考虑一种方法来比较每个对象的

.specimenNum

javascript function object
2个回答
0
投票

最好的方法是使用闭包

const pAequorFactory = () => {
  let specimenCount = 0; // To keep track of the number of specimens created

  return (dna) => {
    specimenCount++; // Increment the specimen count for each new specimen
    return {
      specimenNum: specimenCount, // Assign a unique specimen number
      dna,

      // Your remaining object properties here
    };
  };
};

// Example usage:
const createSpecimen = pAequorFactory();
const specimen1 = createSpecimen('ATCGATCGATCGATC');
const specimen2 = createSpecimen('GCTAGCTAGCTAGCT');

console.log(specimen1.specimenNum); // Output: 1
console.log(specimen2.specimenNum); // Output: 2

这将在每次调用 createSpecimen 时创建唯一的对象,唯一属性将是 SampleNum。


0
投票

您可以创建一个全局数值并递增它:

let specimenNumId = 0;
const pAequorFactory = dna => {
  return {
    specimenNum: ++specimenNumId,
    dna,

...
© www.soinside.com 2019 - 2024. All rights reserved.