我需要将项目推送到Obj Array中,而现在我多次获得最新记录。
codepen:https://codepen.io/dolezalp/pen/YzXjEoo
const hitpoints = ["one", "two", "three"];
let remapImages = new Array();
const item = new Object();
hitpoints.forEach(function(i, index) {
item.img = document.getElementById(i);
item.hit = document.getElementById(i).offsetTop - window.innerHeight;
console.log(item);
remapImages.push(item);
});
console.log(remapImages);
<ul>
<li id="one">1</li>
<li id="two">2</li>
<li id="three">3</li>
</ul>
您应该创建多个对象,否则,您将多次推送同一对象引用:
const hitpoints = ["one", "two", "three"];
let remapImages = new Array();
hitpoints.forEach(function(i, index) {
const item = new Object();
item.img = document.getElementById(i);
item.hit = document.getElementById(i).offsetTop - window.innerHeight;
console.log(item);
remapImages.push(item);
});
console.log(remapImages);
由于它是一个引用,因此它会在foreach循环中更新,这就是为什么您多次看到该对象的最新值的原因。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句