例如我有listings数组:
[ { name: 'bob', price: '10' }, { name: 'jack', price: '12' } ]
我正在尝试找到最低卖家并稍后使用它的数据。我愿意var currentLowestSeller = listings[0];
现在currentLowestSeller是:
{ name: 'bob', price: '10' }
后来我做了更改,currentLowestSeller但我不想listings更改主数组。我currentLowestSeller.price = currentLowestSeller.price * 0.5;这样做了,这个列表数组看起来像这样:
[ { name: 'bob', price: 5 }, { name: 'jack', price: '12' } ]
我该如何防止这种情况?
如果你想重新创建它,只需运行以下代码:
var listings = [];
var name1 = 'bob';
var name2 = 'jack';
var price1 = '10';
var price2 = '12';
listings.push({
name: name1,
price: price1
})
listings.push({
name: name2,
price: price2
})
var currentLowestSeller = listings[0];
currentLowestSeller.price = currentLowestSeller.price * 0.5;
console.log(listings);
我尝试过的:
我尝试在执行任何操作之前创建数组的副本listings。
var unchangedListings = listings;
var currentLowestSeller = listings[0];
currentLowestSeller.price = currentLowestSeller.price * 0.5;
console.log(unchangedListings);
但这没有用。
后来我决定这const unchangedListings = listings;会有所帮助。但由于某种原因,它也会更改定义为常量的值。
开心每一天1111
叮当猫咪
莫回无
慕尼黑5688855
相关分类