繁体   English   中英

JavaScript-加法赋值运算符为什么不能按预期工作?

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

我目前正在用一些动画增强网站。

我尝试了这段代码:

// 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';    
    }
  }
};

它没有用。

我在代码中写了一些console.logs:分配后,“ opacity”始终保持在0.1。

我所期望的是:0.0-0.1-0.2-0.3 ...

现在,我使用以下代码:

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

工作正常。 但是我仍然想知道为什么使用组合的赋值加法运算符会失败。

有人知道吗?

您正在将字符串与Number相加,因此在第一种情况下,您实际上是在连接值

参见此处: https : //developer.mozilla.org/es/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#Addition_assignment

第二种方法有效,因为您正在将css['opacity']转换为数字: +css['opacity']

尝试这个:

  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']是一个字符串。 如果在字符串中添加数字,它将把数字转换为字符串,并连接最后两个字符串。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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