【发布时间】:2017-09-10 19:27:23
【问题描述】:
我有一个包含七个值的数组,它可能会或可能不会被扩展。然后我有一个变量foo,它介于 1 和 -1 之间。基于foo,我选择了我的数组中的一个元素,但我对当前的解决方案并不满意。
有没有首选的方法?
例子:
// Of course there's useful data in no order like the alphabet
var myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
var foo = myFunc(); // Changes often between about 1 and -1
var index;
if (foo >= 0.1) {
index = 6;
} else if (foo < 0.1 && foo >= 0.0) {
index = 5;
} else if (foo < 0.0 && foo >= -0.1) {
index = 4;
} else if (foo < -0.1 && foo >= -0.2) {
index = 3;
} else if (foo < -0.2 && foo >= -0.3) {
index = 2;
} else if (foo < -0.3 && foo >= -0.4) {
index = 1;
} else {
index = 0;
}
var element = myArray[index];
谢谢!
【问题讨论】:
标签: javascript arrays if-statement indexing