我試圖保存從「onclick」檢索到的值,並且還保存以前從單擊按鈕時在「onclick」中檢索到的值。Javascript,保存onclick的值並保存數組中的以前的值
但似乎在使用「for循環」時,即使這些值分別保存在不同的數組中,新檢索的值也會覆蓋先前檢索的數據。
我現在很困惑,有人知道爲什麼嗎?
(如果你按下按鈕 「刷新」,你可以看到,保存當前值。)
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>
'預置值= firstValue;'不創建的副本;它只會導致'preValue'指向內存中的同一個數組。試試這個:'preValue = firstValue.splice();' –