This is my code so far,and it can’t get the expected result,so I guess there is something wrong in my code. result[i]=new Array().push(strArr[i]);
If can’t write like this,Can anyone tell me how to create a new empty array in another array in a loop.
Your code so far
function pairElement(str) {
function pair(arr){
switch(arr[0]){
case "A":
arr.push("T");
break;
case "T":
arr.push("A");
break;
case "C":
arr.push("G");
break;
case "G":
arr.push("C");
break;
}
}
let strArr=str.split("");
let result=[];
for (let i=0;i<strArr.length;i++){
result[i]=new Array().push(strArr[i]);
}
return result.forEach(pair);
}
pairElement("GCG");
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36.
You can declare an empty array before and use it like this.
let array = [];
array.push(strArr[i]);
But notice if you are doing this and saving this into result[i], it’s always going to be 1. You need to make sure to push the array after values are pushed into the array.
for (let i=0;i<strArr.length;i++){
let temp=[];
temp.push(strArr[i]);
result[i]=temp;
}
Sir,as you said,I declared it before i used it.But the result said that TypeError: Cannot read property 'toString' of undefined
And i can’t find out where the error happens.Can you tell me what happened?
Are you using toString method somewhere in your new code?
When I run it with your forloop I am not getting any errors.
function pairElement(str) {
function pair(arr){
switch(arr[0]){
case "A":
arr.push("T");
break;
case "T":
arr.push("A");
break;
case "C":
arr.push("G");
break;
case "G":
arr.push("C");
break;
}
}
let strArr=str.split("");
let result=[];
for (let i=0;i<strArr.length;i++){
let temp=[];
temp.push(strArr[i]);
result[i]=temp;
}
return result.forEach(pair);
}
pairElement("GCG");
It just returns undefined. Try debugging this line.