【发布时间】:2019-04-04 12:13:42
【问题描述】:
我正在研究将任务卡移动到下一列的 StateService 方法。我能够编写工作正常的taskMoveLeft 方法,但我无法使用forEach 循环为taskMoveRight 方法复制它的功能,我只能使用for 循环。
taskMoveLeft 方法的工作示例(使用forEach):
taskMoveLeft(id) {
state.columns.forEach((column, columnIndex) => {
if (state.columns[0] !== column) {
if (column.cards) {
column.cards.forEach((card, cardIndex) => {
if (card.id === id) {
if (state.columns[columnIndex - 1].cards) {
// Add card to the target column card collection
state.columns[columnIndex - 1].cards.push(card);
} else {
// Create target column card collection and add card
state.columns[columnIndex - 1].cards = Array.of();
state.columns[columnIndex - 1].cards.push(card);
}
// Remove the card from the source column card collecion
state.columns[columnIndex].cards.splice(cardIndex, 1);
}
});
}
}
});
}
taskMoveRight 方法的工作示例(使用for 循环):
taskMoveRight(id) {
for (let i = 0; i < state.columns.length; i++) {
if (state.columns[state.columns.length - 1] !== state.columns[i]) {
if (state.columns[i].cards) {
for (let j = 0; j < state.columns[i].cards.length; j++) {
if (state.columns[i].cards[j].id === id) {
if (state.columns[i + 1].cards) {
// Add card to the target column card collection
state.columns[i + 1].cards.push(state.columns[i].cards[j]);
} else {
// Create target column card collection and add card
state.columns[i + 1].cards = Array.of();
state.columns[i + 1].cards.push(state.columns[i].cards[j]);
}
// Remove the card from the source column card collecion
return state.columns[i].cards.splice(j, 1);
}
}
}
}
}
}
无法使taskMoveRight 方法与forEach 循环一起使用。使用此代码,卡片总是移动到最右列:
taskMoveRight(id) {
state.columns.forEach((column, columnIndex) => {
if (state.columns[state.columns.length - 1] !== column) {
if (column.cards) {
column.cards.forEach((card, cardIndex) => {
if (card.id === id) {
// Create target column card collection
if (!state.columns[columnIndex + 1].cards) {
state.columns[columnIndex + 1].cards = Array.of();
}
// Add card to the target column card collection
state.columns[columnIndex + 1].cards.push(card);
// Remove the card from the source column card collecion
state.columns[columnIndex].cards.splice(cardIndex, 1);
}
});
}
}
});
}
【问题讨论】:
-
你为什么要 A) 反转
if条件,以及 B) 删除else? -
另请注意,您尝试替换的
for循环在某些情况下会提前结束。您不能提前终止forEach序列。如果您需要提前终止类似forEach的事情,请使用some(或every),或者在这种情况下可能使用find。 -
实际上是
findIndex。 -
旁注:
Array.of();是写[]的一种非常奇怪的方式。 :-) -
> 你为什么要 A) 反转 if 条件,B) 删除 else?我已经反转它,因为它的代码更少并且逻辑保持不变
标签: javascript arrays loops