【问题标题】:Shorten long if else to get element from array based on value缩短 long if else 以根据值从数组中获取元素
【发布时间】: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


    【解决方案1】:

    有很多方法可以做到这一点,但一种简单的方法可能是:

    index = Math.floor(10 * (0.5 + foo));
    if(index > 6)   index = 6;
    if(index < 0)   index = 0;
    

    【讨论】:

    • 这是 JavaScript,没有 int 也没有类型转换。使用Math.floor
    • 太快了Bergi :-)
    • 太棒了,尽管不像其他解决方案那样可读。简单地使用钳位是个好主意:)
    【解决方案2】:

    解决方案 1: 没有必要进行一些比较,这里有一个更简单的版本:

    if (foo >= 0.1) {
        index = 6;
    } else if (foo >= 0.0) {
        index = 5;
    } else if (foo >= -0.1) {
        index = 4;
    } else if (foo >= -0.2) {
        index = 3;
    } else if (foo >= -0.3) {
        index = 2;
    } else if (foo >= -0.4) {
        index = 1;
    } else {
        index = 0;
    }
    

    解决方案 2:

    double pos[6] = {0.1, 0.0, -0.1, -0.2, -0.3, -0.4};
    int index = 0;
    for (int i = 0; i < 6; i++) {
       if (foo >= pos[i]) {
           index = 6 - i;
           break;
       }
    }
    

    【讨论】:

    • 请注意该问题已标记为javascript :-)
    • 我喜欢第二种解决方案,即使它是 C 或类似的 :) 让我试试!
    • 好的,这非常简单且易于扩展! (使用i &lt; myArray.length)谢谢!
    【解决方案3】:

    您可以使用数组和Array#findIndex 来获取想要的号码。

    const getIndex = v => [-0.4, -0.3, -0.2, -0.1, 0, 0.1, Infinity].findIndex(a => v < a);
    
    console.log(getIndex(-0.5)); // 0
    console.log(getIndex(-0.4)); // 1
    console.log(getIndex(-0.3)); // 2
    console.log(getIndex(-0.2)); // 3
    console.log(getIndex(-0.1)); // 4
    console.log(getIndex(0));    // 5
    console.log(getIndex(0.1));  // 6
    console.log(getIndex(0.2));  // 6
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

    • 抱歉回复晚了,但我已经测试过了,可以让我的其他代码更小!这是巨大的! :)
    猜你喜欢
    • 2020-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-17
    • 1970-01-01
    相关资源
    最近更新 更多