How can I do something like this with a switch statement:
String.prototype.startsWith = function( str ){
return ( this.indexOf( str ) === 0 );
}
switch( myVar ) {
case myVar.startsWith( 'product' ):
// do something
break;
}
This is the equivalent of:
if ( myVar.startsWith( 'product' )) {}
How can I do something like this with a switch statement:
String.prototype.startsWith = function( str ){
return ( this.indexOf( str ) === 0 );
}
switch( myVar ) {
case myVar.startsWith( 'product' ):
// do something
break;
}
This is the equivalent of:
if ( myVar.startsWith( 'product' )) {}
Share
Improve this question
asked Aug 15, 2011 at 1:18
HyderAHyderA
21.4k48 gold badges116 silver badges183 bronze badges
4 Answers
Reset to default 8You can do it, but it's not a logical use of the switch
command:
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;
}
Best way to do this by adding ternary operator, Try this it should work perfectly
let myVar = 'product 42';
switch (myVar) {
case myVar.startsWith('product') ? myVar : false :
alert(1); // do something
break;
}
Like this:-
var x="product";
switch({"product":1, "help":2}[x]){
case 1:alert("product");
break;
case 2:alert("Help");
break;
};
You could do something like 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;
}