【发布时间】:2011-11-07 20:47:03
【问题描述】:
(请参阅下面的示例以完全理解我的要求)
我有一系列项目,我将根据用户的选择将其他项目放入其中并从中删除项目。这个数组总是有一个不超过 30 个项目的连续项目的“活动集”(当项目的总集小于 30 时,它只小于 30,否则它必须是满的)。用户可以更改活动集的开始。
我想知道什么是“最干净”的代码,以及检查列表中添加/删除的新项目是否部分或全部属于活动集中的最有效方法? (另外,如果当前总共有 10 个项目,从而使活动集项目为 0-9,并且他们在项目 0 前面添加了 10 个项目 - 这使得项目 0 成为项目 10 - 那么我希望能够知道改变活动集到新项目 0 到项目 19)
示例:
//For this example, I'm making the active set be 10 items so I can write less
var activeSetLength = 10;
//The total set
var allItems = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o" ];
//First item in active set (in this example, this makes "m" the last active item)
var activeSet = allItems.slice( 3, 3 + activeSetLength );
/*
* Now imagine the user is trying to add items into our list, how best do I handle
* figuring out whether to add them to the activeset list?.
*/
//Adding items into list at position 1 (so only some of these will now be in the active set)
addItems( [ "one", "two", "three", "four" ], 1 );
如果您需要更多解释,请告诉我,因为这可能不是最清楚的问题。谢谢!
注意:在“现实世界”中,我的 activeSet 被实现为 DOM 节点,因此通过 appendChild/insertBefore/removeChild 更改其中的项目(添加此注释以进行澄清)
【问题讨论】:
-
添加项目后,你不能重新分配你的activeSet变量吗?
-
@Brian 不,在“现实世界”中,我的活动集实际上是一个 DOM 节点。所以我实际上需要 appendChild/insertBefore/removeChild 来更改其中的节点。 (我没有包含该信息,因为我认为它会增加复杂性,从而分散实际问题的注意力,抱歉)
-
你使用jquery吗?您可以使用 javascript 向 DOM 节点添加和删除类属性,以跟踪哪些是活动的。
-
我猜这不是一个真正的数组。您不能按整数对每个项目进行索引吗?
-
由于您可以使用 javascript 创建和删除 DOM 节点,另一种可能的解决方案是删除所有“activeSet”节点,然后在添加项目时重新创建一个新的“activeSet”节点列表。
标签: javascript arrays algorithm math mathematical-optimization