处理开关语句的情况

4
如何使用switch语句实现类似以下的操作:
String.prototype.startsWith = function( str ){
    return ( this.indexOf( str ) === 0 );
}

switch( myVar ) {
    case myVar.startsWith( 'product' ):
        // do something 
        break;
}

这相当于:
if ( myVar.startsWith( 'product' )) {}
4个回答

8

您可以这样做,但这并不是使用 switch 命令的逻辑方式:

String.prototype.startsWith = function( str ){
    return ( this.indexOf( str ) === 0 );
};

var myVar = 'product 42';

switch (true) {
    case myVar.startsWith( 'product' ):
        alert(1); // do something
        break;
}

2
你是正确的,如果那是唯一的方法,那么那不是正确的方式。 - HyderA

3

通过添加三元运算符来实现最佳方法, 尝试以下代码,应该可以完美地解决问题。

var myVar = 'product 42';
switch (myVar) {
   case myVar.startsWith('product') ? myVar : '' :
   alert(1); // do something
   break;
 }

<script async src="//jsfiddle.net/arabhossain/Lskq4nar/4/embed/"></script>


0

像这样:

var x="product";

switch({"product":1, "help":2}[x]){
case 1:alert("product");
    break;
 case 2:alert("Help");
    break;
};

1
匹配整个字符串,而不是字符串的开头。 - Guffa

0
你可以这样做:this
BEGINNING = 0;
MIDDLE = 1;
END = 2;
NO_WHERE = -1;

String.prototype.positionOfString = function(str) {
    var idx = this.indexOf(str);

    if (idx === 0) return BEGINNING;
    if (idx > 0 && idx + str.length === this.length) return END;
    if (idx > 0) return MIDDLE;
    else return NO_WHERE;
};

var myVar = ' product';

switch (myVar.positionOfString('product')) {
case BEGINNING:
    alert('beginning'); // do something
    break;
case MIDDLE:
    alert('middle');
    break;
case END:
    alert('END');
    break;
default:
    alert('nope');
    break;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接