For example, I have a toggle button, which would show the current selected element, and would show next element when it is clicked, and it can loop back to first element. I have 2 ways to store the current selected element:
1.Use a variable i to store the selected index:
<button id="b" onclick="onButtonPressed()"/>
<button onclick="onSubmit()">Submit</button>
<script>
let i=0;
let arr=['Red','Yellow','Green','Blue'];
function onButtonPressed(){
i=i++%arr.length;
document.getElementById('b').innerHTML=arr[i];
}
document.getElementById('b').innerHTML=arr[i]
function onSubmit(){
//call url:xxxxx.com/submit?value=arr[i]
}
</script>
2.Use first position as the selected element
<button id="b" onclick="onButtonPressed()"/>
<button onclick="onSubmit()">Submit</button>
<script>
let arr=['Red','Yellow','Green','Blue'];
function onButtonPressed(){
arr.push(arr.shift());
document.getElementById('b').innerHTML=arr[0];
}
document.getElementById('b').innerHTML=arr[0]
function onSubmit(){
//call url:xxxxx.com/submit?value=arr[0]
}
</script>
If both method can be used, and I don't care the initial position of elements, which one should I use?