Javascript 处理开关箱
如何使用switch语句执行类似操作:Javascript 处理开关箱,javascript,switch-statement,Javascript,Switch Statement,如何使用switch语句执行类似操作: String.prototype.startsWith = function( str ){ return ( this.indexOf( str ) === 0 ); } switch( myVar ) { case myVar.startsWith( 'product' ): // do something break; } 这相当于: if ( myVar.startsWith( 'product
String.prototype.startsWith = function( str ){
return ( this.indexOf( str ) === 0 );
}
switch( myVar ) {
case myVar.startsWith( 'product' ):
// do something
break;
}
这相当于:
if ( myVar.startsWith( 'product' )) {}
您可以这样做,但这不是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;
}
像这样:-
var x="product";
switch({"product":1, "help":2}[x]){
case 1:alert("product");
break;
case 2:alert("Help");
break;
};
你可以这样做:
最好的方法是添加,试试这个,它应该工作得很好
var myVar = 'product 42';
switch (myVar) {
case myVar.startsWith('product') ? myVar : '' :
alert(1); // do something
break;
}
你是对的,如果这是唯一的方法,那么这不是匹配整个字符串的正确方法,而不是字符串的开头。
var myVar = 'product 42';
switch (myVar) {
case myVar.startsWith('product') ? myVar : '' :
alert(1); // do something
break;
}