获取 javascript 值,其中范围是数组中的索引
我可能会以完全错误的方式解决这个问题,但从伪代码角度来看,这就是我想做的:
ranges = new Array([0 - 400] = 'dog',
[401 - 1000] = 'cat',
[1001 - 1233] = 'rat');
alert(ranges[243]);
并神奇地让“狗”在我的屏幕上弹出。 (不循环数组,对值执行 > 和 < 等。)
现在,我很清楚你不能做那么简单的事情,但我完全不知道如何做这样的事情 想法? :)
I'm probably going about this in entirely the wrong way, but pseudocode-wise, this is what I'd like to do:
ranges = new Array([0 - 400] = 'dog',
[401 - 1000] = 'cat',
[1001 - 1233] = 'rat');
alert(ranges[243]);
and magically get 'dog' pop up on my screen. Now, I'm well aware you can't do something that simple, but I have absolutely no idea how to do something like this (without looping through an array, performing a > and < on a value etc..)
Any ideas? :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好吧,您可以用所有重复项填充一个简单的数组:
更明智的选择可能是使用某种实际上保存每个范围的低值和高值的数据结构:
或者您可以结合这两种方法:传递范围数据结构将低值和高值传递给函数,该函数根据第一种方法使用该信息填充另一个数组。
Well you could populate a simple array with all the duplicates:
A more sensible option might be to use some kind of data structure that actually holds the low and high values of each range:
Or you could combine the two approaches: pass the ranges data structure with the low and high values to a function that uses the information to populate another array as per the first approach.
这个非常简单明了 - 尽管它假设您不希望范围中出现“漏洞”。本例中没有错误处理,但本质上您只需要传递上限,下限是隐式的。
This one is very simple and straightforward - though it assumes that you don't want "holes" in your ranges. No error handling in this example, but essentially you just need to pass upper bounds, lower bounds are implicit.
您可以完全填充数组 sp ,您可以在运行时将直接索引 dp 到数组中。一旦创建了原始数据结构,运行时速度会很快,但存储效率不高。我通常不建议这样做,但要构建数组:
或者,在更紧凑的结构中,您可以使用如下数据结构和函数:
您还可以使用数组中具有隐式位置的直接数组(代码和数据)更紧凑一些,但可读性都稍差):
You could fully populate an array sp you can dp a direct index into the array at run-time. Once the original data structure is created, that will be fast at run-time, but not very storage efficient. I generally wouldn't recommend this, but to build the array:
Or, in a more compact structure, you can use a data structure and function like this:
You could also use a straight array with implicit positions in the array (code and data are a little more compact, but both are a bit less readable):