简体   繁体   English

添加到数组中的额外元素

[英]Extra elements being added to an array

I was attempting to complete this problem as a newbie, and i'm seeing extra elements within my returned array after my loop.我试图以新手的身份解决这个问题,并且在循环后我在返回的数组中看到了额外的元素。

In DNA strings, symbols "A" and "T" are complements of each other, as "C" and "G". 
You have function with one side of the DNA, you need to get the other complementary side.

Here is my solution这是我的解决方案

let dnaComStrand = [];
const DNAStrand = function (dnaStrand) {
  for (let i = 0; i < dnaStrand.length; i++) {
    if (dnaStrand[i] === `A`) {
      dnaComStrand[i] = `T`;
    } else if (dnaStrand[i] === `T`) {
      dnaComStrand[i] = `A`;
    } else if (dnaStrand[i] === `C`) {
      dnaComStrand[i] = `G`;
    } else if (dnaStrand[i] === `G`) {
      dnaComStrand[i] = `C`;
    }
  }
  //   return dnaComStrand.join(``);
  return dnaComStrand;
};
console.log(DNAStrand(`GCATA`));

yet in the console I was seeing然而在我看到的控制台中

Array(5) [ "C", "G", "T", "A", "T" ]

which became even more confusing if I tried to call the function again.如果我再次尝试调用该函数,这会变得更加混乱。

console.log(DNAStrand([`T`, `C`, `G`]));

resulted in导致

Array(5) [ "A", "G", "C", "A", "T" ]

Where are these extra elements coming from??这些额外的元素是从哪里来的?? Thanks in advance提前致谢

You can do:你可以做:

 const hash = { A: 'T', T: 'A', C: 'G', G: 'C', } const DNAStrand = dnaStrand => dnaStrand.split('').map(c => hash[c]) // 1 const dnaComStrand1 = DNAStrand(`GCATA`) console.log(dnaComStrand1) // 2 const dnaComStrand2 = DNAStrand(dnaComStrand1.join('')) console.log(dnaComStrand2)

使用函数内部和循环之前的一组新元素重新初始化数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM