javascript - 尝试更改对象属性内的数组值
问题描述
我正在做一个项目,我需要在存储在对象属性中的数组中选择一个随机元素,然后使用方法将其更改为其他内容。这是项目的步骤:
.mutate() 负责在对象的 dna 属性中随机选择一个碱基,并将当前碱基更改为不同的碱基。然后 .mutate() 将返回对象的 dna。
例如,如果随机选择的碱基是第一个碱基并且是“A”,则必须将碱基更改为“T”、“C”或“G”。但它不能再次是“A”。
当我尝试这样做时,我的输出总是这样结束:第一个数组是原始数组 ['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())
解决方案
改变
const randomI = Math.floor(Math.random * this.dna.length);
至
const randomI = Math.floor(Math.random() * this.dna.length);
.random()
是一个方法,你需要()
调用它。目前Math.random
评估结果也是如此,NaN
并且您的代码“中断”randomI
NaN
推荐阅读
- mongodb - MongoDB 丰富的查询和隔离保证
- assembly - 在单个操作中将特定位从寄存器复制到不同寄存器的特定位置
- c# - SpeechSynthesizer 支持什么 SAPI 版本?
- asp.net - 在 asp.net 中跨多个解决方案的会话变量
- c# - WCF Rest 不接受请求中的 xml 声明
- payment - 如何生成 Master Pass 商户 ID/商户 PAN
- git - 重组 git 仓库
- c# - 在 powershell 脚本中使用 c# 函数的正确语法是什么?
- r - 如何通过 2+ 个条件自定义因子变量的订单级别?
- sql - 向表格查询添加日期条件