2017-03-28 36 views
0

我試圖保存從「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>

+0

'預置值= firstValue;'不創建的副本;它只會導致'preValue'指向內存中的同一個數組。試試這個:'preValue = firstValue.splice();' –

回答

0

在JavaScript數組就像對象。當你指定: preValue = firstValue;這只是對變量的引用,因此你無法複製該值。

爲了實現這一點,您需要將該數組的每個值複製到先前的值數組中。因此,您可以爲第一次到上一次分配運行另一個循環:

for (var i = 0; i < 1; i++) { 
    prevValue[i] = firstValue[i]; 
} 

假設它們具有相同的大小。

0

請參閱該代碼將工作,

firstValue是後,這將舊值分配給預置值陣列已存值數組。

var firstValue = []; 
 
var preValue = []; 
 

 

 

 
function returneD(a){ 
 

 
    preValue = a; 
 
    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>