这个让我大吃一惊!
我有一个项目列表:
var prev = 'sally.charlie.ted';
var next = 'tina.heather.david';
然后我想向前和向后循环它们,每个延迟1秒:
animate(prev, function () {
animate(next, function () {
console.log('done');
}, false);
}, true);
但现在我迷惑自己。也许这些是更好的方法吗?
function animate(url, callback, reverse, index, length) {
var items = url.split('.'),
total = items.length - 1;
if (typeof index === 'undefined') { index = reverse ? items.length - 1 : 0; }
if (typeof length === 'undefined') { length = reverse ? url.length + items[index].length + 1 : 0; }
if (index > total || index < 0) {
callback();
} else {
if (reverse === true) {
length -= items[index].length + (items.length - index);
} else {
length += items[index].length + index;
}
console.log(url.length, total, length, items[index], url.slice(0, length));
window.setTimeout(function () {
animate(url, callback, reverse, reverse ? index - 1 : index + 1, length);
}, 1000);
}
}
我希望为每个项目获得正确的完整路径,无论是向前还是向后。我想要的输出结果将是:
ted = sally.charlie.ted
charlie = sally.charlie
sally = sally
然后前进:
tina = tina
heather = tina.heather
david = tina.heather.david
这是一个工作小提琴:
答案 0 :(得分:0)
我已经改变了一些你的代码。
试试这个。
function animate(url, callback, reverse, index) {
var items = url.split('.'),
length = 0;
if (typeof index === 'undefined') { index = reverse ? items.length - 1 : 0; }
if (index >= items.length || index < 0) {
callback();
} else {
length = url.indexOf(items[index]) + items[index].length;
console.log(url.length, items[index], url.slice(0, length));
window.setTimeout(function () {
animate(url, callback, reverse, reverse ? index - 1 : index + 1);
}, 1000);
}
}
运行它我得到了这个日志:
17 "ted" "sally.charlie.ted"
17 "charlie" "sally.charlie"
17 "sally" "sally"
18 "tina" "tina"
18 "heather" "tina.heather"
18 "david" "tina.heather.david"