我正在尝试使用数组(' selectedWorkshops'),并将其中的对象移至注册的工作室'。然后,我还要从所选的工作坊'中删除这些对象。另一个阵列简称为“工作坊”。
请在此处查看我的codepen:http://codepen.io/trueScript/pen/wBVqNN
阵列:
var workshops = [
{
name: 'apples',
WorkshopId: '19'
},
{
name: 'oranges',
WorkshopId: '3b'
},
{
name: 'pears',
WorkshopId: 'x6'
},
{
name: 'pineapples',
WorkshopId: '55'
},
{
name: 'watermelons',
WorkshopId: '8v'
}
];
var selectedWorkshops = [
{
name: 'oranges',
WorkshopId: '3b'
},
{
name: 'watermelons',
WorkshopId: '8v'
},
{
name: 'pears',
WorkshopId: 'x6'
}
];
var registeredWorkshops = [];
应该将研讨会转移到注册工作坊'并从选定的工作坊'中删除它们和'研讨会':
flipWorkshops = function(){
var numberOfWorkshops = selectedWorkshops.length;
var X = 1;
for(var i = 0; i < numberOfWorkshops; i++ ){
registeredWorkshops.push(selectedWorkshops[i]);
for(var j = 0, arrayLength = workshops.length; j < arrayLength; j++) {
var selectedWorkshop = selectedWorkshops[i];
var originalWorkshop = workshops[j];
if(selectedWorkshop == originalWorkshop){
var matchingWorkshop = j;
workshops = workshops.splice(j, 1);
selectedWorkshops = selectedWorkshops.splice(i, 1);
}
}
}
};
flipWorkshops();
为什么没有将对象正确地拼接出&#39;工作室&#39;和&#39;选择的工作坊&#39;像他们应该的阵列?我做错了什么?
答案 0 :(得分:2)
“splice()方法在数组中添加/删除项目,并返回删除的项目。” http://w3schools.com/jsref/jsref_splice.asp因此,基本上,您正在将研讨会简化为单个对象,即已删除的数组元素。
相反,改变:
workshops = workshops.splice(j, 1);
selectedWorkshops = selectedWorkshops.splice(i, 1);
...为:
workshops.splice(j, 1);
selectedWorkshops.splice(i, 1);
也许这就是你想要的:
var registeredWorkshops = [];
var flipWorkshops = function(){
var numberOfWorkshops = selectedWorkshops.length;
var X = 1;
for(var i = numberOfWorkshops - 1; i >= 0; i-- ){
registeredWorkshops.push(selectedWorkshops[i]);
var selectedWorkshop = selectedWorkshops[i];
for(var j = workshops.length - 1; j >= 0; j--) {
var originalWorkshop = workshops[j];
if(selectedWorkshop.name == originalWorkshop.name &&
selectedWorkshop.WorkshopId == originalWorkshop.WorkshopId){
var matchingWorkshop = j;
workshops.splice(j, 1);
selectedWorkshops.splice(i, 1);
}
}
}
};
flipWorkshops();
修正splice
,按照jwatts1980的建议颠倒循环,将selectedWorkshop
var移出循环,并比较每个对象项,而不是比较对象,因为{ {3}}