[英]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. 我在代码中写了一些console.logs:分配后,“ opacity”始终保持在0.1。
What I expected was: 0.0 - 0.1 - 0.2 - 0.3 ... 我所期望的是: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 您正在将字符串与Number相加,因此在第一种情况下,您实际上是在连接值
See here: https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#Addition_assignment 参见此处: 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']
第二种方法有效,因为您正在将css['opacity']
转换为数字: +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. css['opacity']
是一个字符串。 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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.