如何使用switch语句执行类似操作:
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;
};
您可以进行类似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;
}
添加ternary operator的最佳方法,尝试此方法可以正常工作
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>