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)
你可以这样做,但这不是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)