为什么所有的数组都在此集合中删除一个元素而不是被引用的元素?
我的代码:
uniformPieces3 = ['company1_hat', 'company1_glasses', 'company2_hat']
uniformSet3 = ['hat', 'glasses']
f1 = function(uniformSet, uniformPieces) {
uniformPieces.sort();
let arr1 = []
for (i = 0; i < uniformPieces.length; i++){
arr1[i] = uniformPieces[i].substr(0, uniformPieces[i].indexOf('_'))
}
let hold = new Set(arr1);
let missingPieces = new Set
hold.forEach(element => missingPieces[element] = uniformSet);
uniformPieces.forEach(e=>{
let t = e.split('_');
if(missingPieces.hasOwnProperty(t[0])){
var index = missingPieces[t[0]].indexOf(t[1]);
if (index !== -1) {
console.log(t[0])
missingPieces[t[0]].splice(index, 1);
}
}
});
console.log(missingPieces)
}
f1(uniformSet3, uniformPieces3);
当我在错误点上调用 splice()
时,它在每个数组中删除一个元素,而不是集合中的数组。例如:
Set(0) {
company1: [ 'hat', 'glasses' ],
company2: [ 'hat', 'glasses' ]}
然后缺失[t [0]]。剪接(index,1)
被调用,它应该删除一个元素,而是产生:
Set(0) { company1: [ 'hat' ], company2: [ 'hat' ] }
从集合中的所有数组中删除该元素。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为在快速阅读时,您正在存储相同的参考(
simerferet
),因此,当您拼接一个引用时,它会拼接全部(因为它们实际上是相同的引用)尝试复制
code> solifterset
而不是直接分配(我没有测试)
I think at a quick read over, you are storing the same reference (
uniformSet
) and so when you splice one, it splices all (because they are all actually the same referrence)try copying
uniformSet
instead of assigning it directly(I didn't test this)
非主要数据类型为通过参考通过。如果您想创建一个副本而不是为同一参考创建另一个变量,则需要克隆/复制所有值。如果您在此处使用第二行,则
my_object
和enose_variable_for_same_reference
请参阅同一对象。Non-primitive data types are passed by reference. If you would like to create a copy instead of creating another variable for the same reference, you need to clone/copy all values. If you use the second line here,
my_object
andanother_variable_for_same_reference
refer to the same object.