处理开关案例

Hyd*_*erA 2 javascript switch-statement

我怎么能用switch语句做这样的事情:

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

switch( myVar ) {
    case myVar.startsWith( 'product' ):
        // do something 
        break;
}
Run Code Online (Sandbox Code Playgroud)

这相当于:

if ( myVar.startsWith( 'product' )) {}
Run Code Online (Sandbox Code Playgroud)

Guf*_*ffa 7

可以这样做,但这不是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;
}
Run Code Online (Sandbox Code Playgroud)

  • 你是对的,如果这是唯一的方法,那么这不是正确的方法 (2认同)