我现在正在研究一个方程,但我的大脑在欺骗我。 我有一些变量:
var infiniteCount,
itemIndex,
itemCount = 6,
itemsToShow = 3,
itemsOffScreen = itemsToShow * 3;
这只是一个例子。 在我添加项目并反向循环项目后,我想出了一个方程来计算项目索引(我希望这是有道理的)。 我想出的等式是这样的:
itemIndex = (itemsOffscreen - (infiniteCount * 2)) + ((itemCount - infiniteCount) - 1);
它有效。如果我将 itemsToShow 更改为 6,索引仍然正确。 要查看正在运行的代码,如下所示:
// Set up infinite
var _setupInfinite = function (items, options) {
// Are we infinite
var i,
infiniteCount,
itemIndex,
itemCount = items.length,
itemsToShow = options.display.itemsToShow || itemCount,
itemsOffscreen = itemsToShow * 3,
isEven = items.length % 2 == 0;
// If we are scrollable
if (options.scrollable && options.infinite) {
// If we need to duplicate some items
if (itemsOffscreen > itemCount) {
// Set our counter to the amount we need to duplicate
infiniteCount = itemsToShow;
// Get our index (it won't change as we are always adding to the beginning of the array)
itemIndex = (itemsOffscreen - (infiniteCount * 2)) + ((itemCount - infiniteCount) - 1);
// Add items to the beginning of our array
for (i = itemsOffscreen; i > (itemsOffscreen - infiniteCount) ; i--) {
// Copy our item
var item = angular.copy(items[itemIndex]);
item.active = false;
// Add to the beginning of the array
items.unshift(item);
}
// Add items to the end of our array
for (i = 0; i < infiniteCount; i++) {
// Get our index
itemIndex = i + infiniteCount;
// Copy our item
var item = angular.copy(items[itemIndex]);
item.active = false;
// Add to the end of the array
items.push(item);
}
}
}
};
所以,问题出在那个表达上。对我来说这似乎很复杂。 我确信它可以被简化。 所以我想我只是想知道是否有人知道怎么做?
最佳答案
使用基本算术简化:
(itemsOffscreen - (infiniteCount * 2)) + ((itemCount - infiniteCount) - 1)
=
itemsOffScreen - infiniteCount * 2 + itemCount - infiniteCount - 1
=
itemsOffScreen + itemCount - infiniteCount * 3 - 1
无论如何,您应该选择最具可读性的版本。
关于javascript - 尝试简化 JavaScript 中的方程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38337051/