[英]Why does assignment with help from ternary operator doesn't work as expected in JS?
[英]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.