Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/403.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 处理开关箱_Javascript_Switch Statement - Fatal编程技术网

Javascript 处理开关箱

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

如何使用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;
};

你可以这样做:


最好的方法是添加,试试这个,它应该工作得很好

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;
 }