如果键不存在,如何获取关联 JavaScript 数组中最近的键索引?
所以,尝试这样做可能是一件奇怪的事情,但我很好奇是否可能:
假设我有一个像这样的关联数组:
myarray[50] = 'test1'
myarray[100] = 'test2'
当然,我可以通过它的键访问 'test1'
:
myarray[50]; // returns 'test1'
但是有没有一种方法,如果我有一个索引键“60”,我可以在数组中查找,如果键 60 不存在,则获取下一个的值“最近的”键,“50”?
这个的用例是我正在尝试为视频设置提示点,如果用户寻找并错过了提示点,我想显示来自用户寻求的最后一个提示点的信息。
我想我可以使用“in”运算符检查密钥是否存在。但如果没有找到,我怎样才能获得确实存在的“前一个”或“下一个最小”数组键?
我假设执行此操作的唯一方法是迭代数组,保存“最后一个”索引值,直到找到“index > myKey”的退出条件。问题是,如果这是一个包含大量队列点的长视频,并且用户频繁搜索,则每次迭代整个提示点数组可能会很慢。有没有更好、更快的方法来做到这一点?
So, this might be a weird thing to try to do, but I'm curious if it's possible:
Say I have an associative array like this:
myarray[50] = 'test1'
myarray[100] = 'test2'
I can access 'test1'
by it's key, of course:
myarray[50]; // returns 'test1'
But is there a way where if I have an index key of '60', that I can look in the array and if key 60 isn't there, get the value of the next "closest" key, '50'?
The use-case for this is that I am trying to set up cue-points for a video, and if the user seeks and misses a cue point, I want to display the information from the last cue point the user seeked beyond.
I think I can check for the existence of the key with the 'in' operator. But if it's not found, how can I get the "previous" or "next smallest" array key that DOES exist?
I assume the only way to do this is to iterate through the array, saving the "last" index value until the exit condition of "index > myKey" is found. The thing is, if it's a long video with lots of queue points and the user seeks frequently, iterating through the entire array of cue points each time might be slow. Is there a better, faster way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须编写自己的函数:
您还可以将其添加为数组原型的方法,以使(我认为)更具可读性:
You'd have to write your own function:
You could also add this as a method of the Array prototype, to make (what I think) is more readable: