简体   繁体   中英

JavaScript - Why doesn't the addition assignment operator work as expected?

I'm currently enhancing a website with a few animations.

I tried this code:

// Opacity is 0 in the beginning. Set 
//  in CSS. 
// 1. Parameter: Boolean - true if making the
//  element visible; false if making it vanish.
// 2. Parameter: Object

var changeOpacity = function(direction, element) {
  var css = element.style;
  var goStep = function(signedStep) {
    css['opacity'] += signedStep;
    changeOpacity(direction, element);
  };

  if (direction) {
    if (css['opacity'] < 1.0) {
      setTimeout(function() {
        goStep(0.1);
      }, timeStep);
    }
  } else {
    if (css['opacity'] >= 0.1) {
      setTimeout(function() {
      goStep(-0.1);
  }, timeStep);
    } else {
      css['display'] = 'none';    
    }
  }
};

It haven't worked.

I wrote a few console.logs in the code: 'opacity' always stayed at 0.1 after the assignment.

What I expected was: 0.0 - 0.1 - 0.2 - 0.3 ...

Now I use this code:

// ...
var goStep = function(signedStep) {
  css['opacity'] = +css['opacity'] + signedStep;
  changeOpacity(direction, element);
};
// ...

Works fine. But I still wonder why using the combined assignment addition operator failed.

Has anyone an idea?

You are adding string with Number, so in first case you are actually concatenating the values

See here: https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#Addition_assignment

The second aproach works because you are converting css['opacity'] to a number: +css['opacity']

Try this:

  var test = "0.1", test2 = "0.1"; signedStep = 0.1; test += signedStep; alert(test+" is a "+typeof test); test2 = +test2 + signedStep; alert(test2+" is a "+typeof test2); 

css['opacity'] is a string. If you add a number to a string, it will convert the number into a string and concat the two final strings.

css['opactity'] = 0.1
css['opacity'] += 0.5 // => "0.10.5"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM