【问题标题】:Mutation of array数组突变
【发布时间】:2019-12-09 14:21:09
【问题描述】:

由于某种原因,我无法让下面的代码按预期工作。

我已经声明了具有随机 15 个元素的变量 dna,它的每个元素都是来自数组 dnaBases 的随机字母。

Mutate 函数应该使用随机 15 个元素创建新的(类似数组),但第一个数组中的元素不能重复。相反,它们应该被 dnaBases 数组中剩余的三个元素替换。

我的代码中的问题是有时字母会重复,即使在以前的情况下没有。

const dnaBases = ['A', 'T', 'C', 'G']
var dna = []
for (let i = 0; i < 15; i++) {
  dna.push(dnaBases[Math.floor(Math.random() * 4)])
}

function mutate() {
  console.log(dna) // to check newly generated dna array
  var tmp = []
  var newDnaBases = ['A', 'T', 'C', 'G']
  for (var j = 0; j < 15; j++) {
    tmp.push(newDnaBases[Math.floor(Math.random() * 4)]);
  }

  console.log(tmp) // to check newly generated tmp array

  for (var k = 0; k < tmp.length; k++) {
      var randomIndex = Math.floor(Math.random() * 3);
      if (tmp[k] === dna[k]) {
        var x = newDnaBases.splice(tmp[k], 1);
        tmp[k] = newDnaBases[randomIndex];
        newDnaBases.push(x.toString());
      }
  }
  console.log(tmp) // to see how tmp has changed after for loop
  console.log(newDnaBases) // to check if newDnaBases is not corrupted
}

mutate()

我是 Javascript 新手,第一眼看不出问题。

非常感谢!

【问题讨论】:

    标签: javascript arrays loops methods


    【解决方案1】:

    在 js 中,split、slice ou reduce 等数组方法用于返回数组变量的“克隆”以及该方法应用的更改。 喜欢

    a = [1,2,3]
    b = a.filter(i => {
          if (i === 2) {
            return true
          } else {
            return false
          }
    })
    b[0] === 2 // true
    a[2] === 3 // true
    

    所以在你的代码中:

    const dnaBases = ['A', 'T', 'C', 'G']
    var dna = []
    for (let i = 0; i < 15; i++) {
      dna.push(dnaBases[Math.floor(Math.random() * 4)])
    }
    
    function mutate() {
      console.log(dna) 
      var tmp = []
      var newDnaBases = ['A', 'T', 'C', 'G']
      for (var j = 0; j < 15; j++) {
        tmp.push(newDnaBases[Math.floor(Math.random() * 4)]);
      }
    
      console.log(tmp) // to check newly generated tmp array
    
      for (var k = 0; k < tmp.length; k++) {
          var randomIndex = Math.floor(Math.random() * 3);
          if (tmp[k] === dna[k]) {
            var x = newDnaBases.filter(i=> i!== tmp[k]) //returns the array without the repeated item, without altering the original variable
            tmp[k] = x[Math.floor(Math.random() * 2)];
          }
      }
      console.log(tmp)
      console.log(newDnaBases) 
    }
    
    mutate()
    

    【讨论】:

    • 谢谢,我完全忘记了过滤方法。
    • 不客气,顺便说一句,如果你正在处理大量的白色数据(真正的 dna 值),我建议你使用 "array Variable".forEach((value,index,orgArray)=&gt;{/* function here*/}),因为它是异步工​​作的,这样你的代码会更优化
    猜你喜欢
    • 1970-01-01
    • 2019-03-15
    • 2018-01-13
    • 2020-09-18
    • 1970-01-01
    • 2016-04-22
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多