In the middle I have a “sanity check” console log that breaks the two steps in half, but when it runs it is ~actually~ logging as if the .forEach section of the code below it has already run (adding the second letter pair to the sub-array), thus is giving me the final answer.
Why does this happen? Does .forEach have a special flag about how it is handled by the interpreter?
I’ve dug around on the .MDN and I’ve only found that .forEach cannot be chained.
function pairElement(str){
var arr = [];
var tempArr = [];
//Step 1.
//Take str, push each char to a sub-array,
//Then push that sub-array into the main array & reset
for (var i = 0; i<str.length; i++){
tempArr.push(str[i]);
arr.push((tempArr));
tempArr = [];
}
//Up to this point, we ~should~ have arr = [["G"],["C"],["G"]]
console.log("Sanity check:",arr);
//Step 2.
//Loop through each subarray, add the companion letter to it
arr.forEach(function addPair(arr){
//console.log(arr[j],"is:",arr[j]);
while (arr.length <= 1){
if (arr[0] == "A"){
arr.push("T");
}
else if (arr[0] == "T"){
arr.push("A");
}
else if (arr[0] == "G"){
arr.push("C");
}
else if (arr[0] == "C"){
arr.push("G");
}
else{
console.log("Something is broken :(");
}
console.log("Add pair done, returning:",arr);
return arr;
}
});
console.log("DONE!",arr);
return arr;
}
pairElement("GCG");
I think it has something to do with the browser’s console (like, it doesn’t give you a snapshot of what the array looks like before you run .forEach, but instead gives you a “link” to the array).
On that linked module it works as you described, but in the FCC courses, jsfiddle, and a local page with tags it gives me the original result: http://imgur.com/rcJ0w2r
It does the same thing in Firefox, as well… weird.