在 JavaScript 回调中使用上次提取内存提取数组值
假设我有一个动态数组,在页面加载时填充了不同数量的字符串:
var arr = ["string1","string2","string3","string4","string5","string6","string7","string8","string9","string10","string11","string12","string13","string14","string15","string16","string17","string18"];
然后我有一个在每个事件(假设单击)上调用的函数,该函数需要连续带回数组的 3 个字符串,同时记住上次调用时它停留在哪个值。所以:
第一次调用函数,它返回:
string1, string2, string3
第二次调用它,它返回:
string4, string5, string6
等等...
我不需要单击事件或回调函数的代码,而是需要该函数的代码每次都会生成提取并将其返回。一些简单的事情,例如能够
arr.runExtraction();
在每个回调上调用:并让它带回所需的数据。
Let's say I have a dynamic array that is populated on page load with various amounts of strings inside:
var arr = ["string1","string2","string3","string4","string5","string6","string7","string8","string9","string10","string11","string12","string13","string14","string15","string16","string17","string18"];
I then have a function that is called on each event (let's say a click) that needs to bring back 3 strings of the array consecutively while remembering which value it left off at, the last time it was called. So:
First time function is called, it returns:
string1, string2, string3
Second time it is called, it returns:
string4, string5, string6
and so on...
I don't the need the code for the click event or the callback function, rather the code for the function that would generate the extraction each time and bring it back. Something simple like being able to call:
arr.runExtraction();
on each callback and having it bring back the desired data.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果数组耗尽会发生什么?从头开始?
您可以执行以下操作:
编辑:添加
start
参数。因为
current
将与values.length
相同> 最后,如果不进行回绕,splice
将返回一个空数组。使用
slice
不会更改原始数组。然后
DEMO
它可能会在“最后”提取中为您提供更少的元素如果元素的数量不能被提取的元素的数量整除。下一次调用将让它再次从头开始。您还可以修改它,使其环绕并从头开始获取元素,以便它始终返回您指定的尽可能多的元素。
参考:
Array.prototype.slice
What should happen if the array is exhausted? Start from the beginning?
You could do something like this:
Edit: Added
start
parameter.As
current
will be the same asvalues.length
in the end,splice
will return an empty array if you don't wrap around.Using
slice
won't change the original array.And then
DEMO
It might give you less elements in the "last" extraction if the number of elements is not divisible by number of extracted elements. The next call will let it start from the beginning again. You could also modify it that it wraps around and takes elements from the beginning so that it will always return as many elements as you have specified.
Reference:
Array.prototype.slice