创建一个动态值从只有一个变量,增加在每次渲染?



我有以下逻辑,可扩展到只有一定程度,换句话说,当达到一定阈值时,我必须为每种情况手动编写逻辑,最大的问题是我只引用一个项目(thisCase),每次渲染都会增加。

是否知道如何能够看到某些动态增量而不必为每种情况手动编写,这个函数是一个实用函数。

let thisCase = 1
// this case increase after render
const increment = () => {
const incementThisCase = () => {
console.log(thisCase + 1)
thisCase = thisCase +1
}
incementThisCase()
if (thisCase > 8 && thisCase < 16) {
alert(8)
}
if (thisCase > 16 && thisCase < 24) {
alert(16)
}
if (thisCase > 24 && thisCase < 32) {
alert(32)
}
};
<div onclick={increment()}>incrment</div>

在这里,只需将thisCase除以8,如下所示

let increment = (thisCase) => {
let i=Math.floor(thisCase/8)+1;
return i*8;

};

这是我的尝试,我认为它很好地解决了你的问题,如果我理解正确的话。

注意:我在你的帖子的评论中看到你增加了1,我的脚本增加了4用于演示目的,但你可以改变这个值和"步骤"。值(= 8在你的问题)

var thisCase = 0; 
var step = 8;
function increment(){
var currentStep = step;
thisCase = thisCase + 4;
console.log('ThisCase = ' + thisCase);
// testing logic
while(thisCase > currentStep){
const max = parseInt(currentStep)+parseInt(step);
if(thisCase < max){
alert(thisCase + ' is between ' + currentStep + ' and ' + max);
return;
}
else currentStep += step;
}
};
<button onclick="increment()">Increment</button>

最新更新