Another Intermediate Algorithm Challenge. I got it to work using a switch nested in a for loop but couldn’t manage with the for in method. I’m trying to have the forEach compare each element in the array to, using the for in, every key in the object. If the element === key, then change the element to the object key’s value.
I consoled everything out as much as I could, but it doesn’t want to work in the forEach loop.
function convertHTML(str) {
let arr = str.split('');
const entities = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
};
arr.forEach((elem) => {
for (let obj in entities) {
if (elem == obj) {
console.log(elem, obj);
elem = entities[obj];
}
}
});
return arr.join('');
}
So in arr.forEach( elem => {});
elem can’t be used to mutate the array with a simple assignment operator (elem = 10, for example). But it can be used to refer to the elements of the array in other ways.?
elem here is not exactly the element of the array, rather it’s an argument to callback function you’re passing to forEach() and depending on the type of the element it might be passed “by value”, meaning changing it will not affect original. You can read more about this here: https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_value
Thanks–I am trying to get out of my comfort zone of using for loops for everything! These higher order methods are more complex and I guess it will take a while for me to get the hang of them.