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

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

本文关键字:不能按 工作 赋值运算符 为什么 JavaScript      更新时间:2023-09-26

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

我尝试了以下代码:

// 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:"不透明度"在分配后始终保持在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

第二个 aproach 有效是因为您要将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"