So I am having a problem changing the value of an array element with the forEach method, the problem is that I am not sure if what I am doing is legal, but I couldn’t find an answer on google.
My code:
function convertHTML(str) {
const specialCharecters = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'"
}
let specialCharectersArr = Object.keys(specialCharecters);
let final = str.split("");
final.forEach(function(char){
if (specialCharectersArr.indexOf(char) !== -1){
char = specialCharecters[char];
console.log(char);
}
});
return final.join("");
}
convertHTML("Dolce & Gabbana");
Chrome console shows “& a m p;”. (I add spaces so it doesn’t show as &)
While FCC console shows “&”.
Within your forEach the logic for grabbing the $amp symbol is fine. That’s why doing console.log() on it is returning $amp; properly.
However, if you do console.log(convertHTML("Dolce & Gabbana")); you’ll see that what your function is returning is still "Dolce & Gabbana". You’re matching the right character and giving the value of $amp; to the string char, but that doesn’t actually change the original string.
forEach doesn’t automatically do anything to change the array that it is looping over. It just loops through the array. The argument you use in its callback function (the function(char){} part) just gives you a copy of that array item through the first selector, not the item itself. In other words, if you were to do char = "" in your forEach loop, it would do absolutely nothing at all.
I really think JavaScript’s map method for arrays would be better here, but if you need to use forEach you can still do it. There’s tons of ways you can go about it.
For example, you could build up a new array and return that. Or you could add an iterator variable
and increase that with each loop, and then you could modify final with final[i] = char (but at that point you really should just use a normal for loop.
Thanks a lot for you response, I knew that forEach returns a copy but I couldn’t find anywhere whether the callback function argument is a reference for the original array elements or just a copy.
I’m glad my advice resulted in a solution for you, but a large part of my point was that forEach doesn’t return a copy, modified or not. It just provides a loop for each item in the array. Take a look at the documentation for forEach. It returns undefined.