i'm trying to save values retrieved from "onclick" and also save the values previously retrieved from "onclick" in different arrays when buttons are clicked.
but it seems like when "for loop" is used, newly retrieved values overwrite previously retrieved data even though those values are saved separately in different arrays.
i'm really confused right now, does anybody know why?
(if you hit the button "refresh", you can see the current values that are saved.)
var firstValue = [];
var preValue = [];
function returneD(a){
preValue = firstValue;
console.log("returned! preValue: "+preValue);
for (var i = 0; i < 1; i++) {
firstValue[i] = a;
console.log("returned! firstValue: "+firstValue);
}
}
function refresh1(){
console.log("preValue: "+preValue);
console.log("firstValue: "+firstValue);
}
<!DOCTYPE html>
<html>
<head>
<script src="jstest.js"></script>
</head>
<body id="thebody">
<button id="1" onclick="returneD(this.id)">O N E</button>
<button id="2" onclick="returneD(this.id)">T W O</button>
<button id="3" onclick="returneD(this.id)">T H R E E</button>
<button id="4" onclick="returneD(this.id)">F O U R</button>
<br>
<button onclick="refresh1()">refresh</button>
</body>
</html>
preValue = firstValue;doesn't create a copy; it only causespreValueto point at the same array in memory. Try this instead:preValue = firstValue.splice();