共享案例的Javascript切换语句

时间:2018-10-06 07:05:29

标签: javascript switch-statement

我创建了一系列执行相似任务的switch语句。

目前我有这样的东西...

// Render meta on cart and checkout
add_filter( 'woocommerce_get_item_data', 'rendering_meta_field_on_cart_and_checkout', 10, 2 );
function rendering_meta_field_on_cart_and_checkout( $cart_item_data, $cart_item ) {
    if( isset( $cart_item['_backorder_text'] ) ) {
        $cart_item_data[] = array( 
            "name" => __( "Backorders text", "woocommerce" ), 
            "value" => $cart_item['_backorder_text'] 
        );
    }
    return $cart_item_data;
}

这是另一个非常相似的switch语句,例如...

switch(seconds % 10) {
    case 0: bs2 = "zero"; 
    break;
    case 1: bs2 = "one"; 
    break;
    case 2: bs2 = "two"; 
    break;
    case 3: bs2 = "three"; 
    break;
    case 4: bs2 = "four"; 
    break;
    case 5: bs2 = "five"; 
    break;
    case 6: bs2 = "six"; 
    break;
    case 7: bs2 = "seven"; 
    break;
    case 8: bs2 = "eight"; 
    break;
    case 9: bs2 = "nine"; 
}
document.getElementById("s2").className = bs2;

这种事情还在继续,但是我敢肯定,你知道这个主意。它可以工作,但是正如您在两个语句中看到的那样,唯一的区别是将结果传递给表达式和className。令我惊讶的是,必须有一种更有效的方法来做同样的事情。有指针吗?

1 个答案:

答案 0 :(得分:2)

您可以通过创建如下所示的函数来简化代码

function getFigure(t) {
var value;
switch(t % 10) {
    case 0: value = "zero"; 
    break;
    case 1: value = "one"; 
    break;
    case 2: value = "two"; 
    break;
    case 3: value = "three"; 
    break;
    case 4: value = "four"; 
    break;
    case 5: value = "five"; 
    break;
    case 6: value = "six"; 
    break;
    case 7: value = "seven"; 
    break;
    case 8: value = "eight"; 
    break;
    case 9: value = "nine"; 
}
return value;
}
var seconds = 8;
var bm = getFigure(seconds);
console.log(bm);

或者您可以进一步维护带有值的数组,并获得如下值

let arr = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];
let seconds = 9;
let minutes = 2;
document.getElementById("s2").className = arr[seconds % 10];
document.getElementById("m2").className = arr[minutes % 10];
.nine {
  color: red;
}
.two {
  color: blue;
}
<div id="s2">Seconds</div>
<div id="m2">Minutes</div>