Reputation: 3
I describe what i've tried to do: i have to get a nested array,which depends on input.At each sub-array must be one pair of two characters.Pairs create from basic pairs: AT,CG. e.g: Input 'CGT' output [['C','G'],['G','C'],['T','A']] i tried this:
function pairElement(str) {
let matched=str.match(/[A-Z]/g); //get array from str
let cookedArr=[]; //the final array
for(let i=0;i<matched.length;i++){ //create nested arr.
for(let j=0;j<3;j++){
switch(matched[i]){
case 'A':
cookedArr[i][j].push('A');
cookedArr[i][j].push('T');
break;
case 'T':
cookedArr[i][j].push('T');
cookedArr[i][j].push('A');
break;
case 'C':
cookedArr[i][j].push('C');
cookedArr[i][j].push('G');
break;
case 'G':
cookedArr[i][j].push('G');
cookedArr[i][j].push('C');}
}}}
pairElement("GCG");
and it appears :TypeError: Cannot read property '0' of undefined I dont understand whats wrong,if switch statement use '===' compaprsion?
Где ошибка, если оператор switch использует '===' сравнение?
Upvotes: 0
Views: 32
Reputation: 370999
The cookedArr
starts out being only an empty array, but in the case
s, you attempt to push to cookedArr[i][j]
- but no sub-array exists at cookedArr[i]
yet, so assigning to cookedArr[i][j]
throws.
Fix it by defining the nested array first, right before the switch
.
To make the code much more concise, you can use an object mapping characters to their arrays:
const baseToPairs = {
C: ['C', 'G'],
G: ['G', 'C'],
T: ['T', 'A']
}
function pairElement(str) {
return [...str].map(char => [...baseToPairs[char]]);
}
console.log(pairElement("GCG"));
Upvotes: 2