gpt4 book ai didi

javascript - 基于For循环迭代的数组拼接

转载 作者:行者123 更新时间:2023-12-02 16:15:39 24 4
gpt4 key购买 nike

我正在尝试获取一个数组(“selectedWorkshops”),并将其中的对象移动到“registeredWorkshops”。然后,我还想从“selectedWorkshops”和另一个简单地称为“workshops”的数组中删除这些对象。

在此处查看我的代码笔: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 = [];

应该将研讨会移动到“registeredWorkshops”并将其从“selectedWorkshops”和“workshops”中删除的函数:

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();

为什么对象没有像应有的那样从“workshop”和“selectedWorkshops”数组中正确拼接出来?我做错了什么?

最佳答案

“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);

JSFiddle

<小时/>

也许这就是你想要的:

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();

按照 jwatts1980 的建议修复了拼接,反转了循环,将 selectedWorkshop 变量移出循环,并比较每个对象项,而不是比较对象,因为 objects don't compare .

JSFiddle Tweaked

JSFiddle Object Compare Example

关于javascript - 基于For循环迭代的数组拼接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29638527/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com