質問

I'm trying to create a function that goes through an objects properties and multiplies the values by 2 if that value is a number.

I'm sure the var value is an integer but it's not applying the multiplication ? Where am I going wrong in this code ?

var menu = {
width: "200",  
height: "300",
title: "My menu"
};

function multiplyNumeric(menu) {

 for(var key in menu) {
    var value = menu[key];
    if( typeof value === 'number' ) {
        value = value * 2;

    }
 }

}

multiplyNumeric(menu);

alert(menu.width);
役に立ちましたか?

解決

Numbers (as well as strings and booleans) are passed by value. You're copying the value the a new variable where you're modifying it.

You need to modify the object's property directly:

for (var key in menu) {
  if (typeof menu[key] === 'number') {
    menu[key] *= 2;
  }
}

Also, JavaScript will not return "number" if you ask for typeof("200"); it will return "string". You need a numeric literal, not a string:

var menu = {
  width: 200,  
  height: 300,
  title: "My menu"
};

他のヒント

Just change the those strings to numbers in your object:

var menu = {
  width: 200,  
  height: 300,
  title: "My menu"
};

edit your object as follow dont use quotes for number at your object

var menu = {
width:200,  
height:300,
title: "My menu"
};
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top