我知道它的基本原理但陷入困境。我試圖將對象添加到數組:將對象添加到陣列會導致重複
的Html
<p>
<label>
<input type="text" name="test1" id="test1" />
</label>
</p>
<p>
<label>
<input type="text" name="test2" id="test2" />
</label>
</p>
腳本
var res = {};
var array_res = [];
function init(){
x= $('#test1').val();
res['x'] = x;
y= $('#test2').val();
res['y'] = y;
array_res.push(res);
return array_res
}
$('#btn').click(function(){
init();
console.log(array_res);
});
當第一加法X = 1且y = 2 I在控制檯得到:
[Object { x="1", y="2"}]
接下來我嘗試插入x = 3和y = 4,然後我得到:
[Object { x="3", y="4"}, Object { x="3", y="4"}]
代替
[Object { x="1", y="2"}, Object { x="3", y="4"}]
這是爲什麼?我嗅到它的一個對象實例問題,但無法弄清楚該怎麼做。在此先感謝
請勿使用全局變量。將'var res = {}'移到init函數中。 – Andreas