Reputation: 69
I have 4 different values (strings) in JavaScript. I need to make a check, if one of these values is not a number. If so, then replace the value with "---", if not, do nothing. So I put the values in an array and called the forEach-function to check. So I actually want my predefined variables (before putting them in an array) to change if they are not a number, but only the elements of the array change.
So I did some researches and I found the difference between call-by-reference and call-by-value. So I changed my variables to String-Objects, but it does not work. I know, hat calling the elements of my array would also work, but I want to understand why my actual variables does not change ?
var first = new String("1");
var second = new String("2");
var third = new String("3");
var fourth = new String("test");
var testArr = [first, second, third, fourth];
testArr.forEach(function (value, index) {
if (isNaN(value)) {
this[index] = "---";
}
}, testArr);
console.log(fourth);
//*here I expect "---" but it is "test"*
//I know that testArr[3] is now "---", but why not the variable fourth as well?
Upvotes: 0
Views: 944
Reputation: 954
Value stored in variables will never be changed, because in your case variable host value itself, not reference. If you want to apply this kind of magic, you should:
Use objects instead of typed variables e.g:
var first = {value:'1'};
var second = {value:'2'};
var third = {value:'3'};
var fourth = {value:'replaceme'};
var testArr = [first, second, third, fourth];
testArr.forEach(function (obj, index) {
if (isNaN(obj.value)) {
obj.value = "---";
}
});
console.log(fourth);
Upvotes: 2