最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Processing switch cases - Stack Overflow

programmeradmin2浏览0评论

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
Add a comment  | 

4 Answers 4

Reset to default 8

You 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;
}
发布评论

评论列表(0)

  1. 暂无评论