如何将计数器变量限制在正整数范围内?
How can a counter variable be restricted to only positive integer range?
我想知道如何限制计数器进入负整数范围。
var i=0;
const plus = function(){
i += 1;
document.querySelector("#demo").innerHTML = `Total Items : ${i}`;
}
const minus = function(){
i -= 1;
document.querySelector("#demo").innerHTML = `Total Items : ${i}`;
}
const clearCart = (() => {
i = 0;
document.querySelector("#demo").innerHTML = `Total Items : ${i}`;
})
您可以检查结果是否为负值并将负值替换为 0。此逻辑可以使用 Math.max
:
来实现
var i=0;
const plus = function(){
i += 1;
document.querySelector("#demo").innerHTML = `Total Items : ${i}`;
}
const minus = function(){
i = Math.max(i - 1, 0);
document.querySelector("#demo").innerHTML = `Total Items : ${i}`;
}
const clearCart = (() => {
i = 0;
document.querySelector("#demo").innerHTML = `Total Items : ${i}`;
})
setTimeout(() => {
plus();
console.log('plus()');
}, 500);
setTimeout(() => {
minus();
console.log('minus()');
}, 1000);
setTimeout(() => {
minus();
console.log('minus()');
}, 1500);
setTimeout(() => {
minus();
console.log('minus()');
}, 2000);
setTimeout(() => {
plus();
console.log('plus()');
}, 2500);
<span id="demo"></span>
我想知道如何限制计数器进入负整数范围。
var i=0;
const plus = function(){
i += 1;
document.querySelector("#demo").innerHTML = `Total Items : ${i}`;
}
const minus = function(){
i -= 1;
document.querySelector("#demo").innerHTML = `Total Items : ${i}`;
}
const clearCart = (() => {
i = 0;
document.querySelector("#demo").innerHTML = `Total Items : ${i}`;
})
您可以检查结果是否为负值并将负值替换为 0。此逻辑可以使用 Math.max
:
var i=0;
const plus = function(){
i += 1;
document.querySelector("#demo").innerHTML = `Total Items : ${i}`;
}
const minus = function(){
i = Math.max(i - 1, 0);
document.querySelector("#demo").innerHTML = `Total Items : ${i}`;
}
const clearCart = (() => {
i = 0;
document.querySelector("#demo").innerHTML = `Total Items : ${i}`;
})
setTimeout(() => {
plus();
console.log('plus()');
}, 500);
setTimeout(() => {
minus();
console.log('minus()');
}, 1000);
setTimeout(() => {
minus();
console.log('minus()');
}, 1500);
setTimeout(() => {
minus();
console.log('minus()');
}, 2000);
setTimeout(() => {
plus();
console.log('plus()');
}, 2500);
<span id="demo"></span>