在Javascript中匹配字符串与字符串数组

问题描述 投票:-1回答:3

    str1 = booking_kode.substring(0, 3);
    B = ["800", "807", "826", "847", "866"];
    C = ["827", "846"];
    E = ["867", "879"];
    F = ["880", "899"];

    if (str1 = array B){
    	print ('Prefix , first 3 digit = ' + str1 + '\n')
    	comm_code = 'B000'
    	print ('Comm_Code = ' + comm_code + '\n')
    }
    else if (str1 = array C) {
	print ('Prefix , first 3 digit = ' + str1 + '\n')
	comm_code = 'C000'
	print ('Comm_Code = ' + comm_code + '\n')
}
    else if (str1 = array E) {
	print ('Prefix , first 3 digit = ' + str1 + '\n')
	comm_code = 'E000'
	print ('Comm_Code = ' + comm_code + '\n')
}
    else if (str1 = array F) {
	print ('Prefix , first 3 digit = ' + str1 + '\n')
	comm_code = 'F000'
	print ('Comm_Code = ' + comm_code + '\n')
}
    else {
	print ('Prefix , Nilai 3 digit pertama = ' + str1 + '\n')
	comm_code = 'D000'
	print ('Comm_Code = ' + comm_code + '\n')
}

你好,

我想知道如何将字符串Str1与数组B,C,E,F的值匹配。

我的意思是 :

If Str1 = 800|| 807 || 826 || 847 || 866, Then Comm_code = B000
If Str1 = 827 || 846 then Comm_code = C000
If Str1 = 867 || 879 then Comm_code = E000
If Str1 = 880 || 899 then Comm_code = F000
Else Default --> Comm_code = D000

请善意的建议。

附: :Fyi,我正在使用EcmaScript 2015 / ES5。

javascript arrays string if-statement ecmascript-5
3个回答
1
投票

只需使用简单的String.prototype.indexOf

str1 = booking_kode.substring(0, 3);
B = ["800", "807", "826", "847", "866"];
C = ["827", "846"];
E = ["867", "879"];
F = ["880", "899"];

if (B.indexOf(str1) > -1)
{
    print ('Prefix , first 3 digit = ' + str1 + '\n');
    comm_code = 'B000';
    print ('Comm_Code = ' + comm_code + '\n');
}
else if (C.indexOf(str1) > -1)
{
    print ('Prefix , first 3 digit = ' + str1 + '\n');
    comm_code = 'C000';
    print ('Comm_Code = ' + comm_code + '\n');
}
else if (E.indexOf(str1) > -1)
{
    print ('Prefix , first 3 digit = ' + str1 + '\n');
    comm_code = 'E000';
    print ('Comm_Code = ' + comm_code + '\n');
}
else if (F.indexOf(str1) > -1)
{
    print ('Prefix , first 3 digit = ' + str1 + '\n');
    comm_code = 'F000';
    print ('Comm_Code = ' + comm_code + '\n');
}
else
{
    print ('Prefix , Nilai 3 digit pertama = ' + str1 + '\n');
    comm_code = 'D000';
    print ('Comm_Code = ' + comm_code + '\n');
}

0
投票

您可以使用Array.indexOf()方法使用简单的if else条件实现此目的。但是请确保str1和数组中的值具有相同的变量类型(字符串或数字)。

   if (B.indexOf(str1) > -1 ) {   //if value exists in B 
        //do soemthing;
    } 
    else if(C.indexof(str1) >-1 ) { //if value exists in C
      //do soemthing
    }

0
投票

解决这个问题的一个可能的解决方案是我们qazxsw poi(我认为它基于Array.some()包含在qazxsw poi中)。首先,您可以创建一个方法来检查ES5是否在link上:

element
array

然后,您的代码可以重做:

function arrayIncludes(arr, ele)
{
     return arr.some(function(x) {return (x === ele);});
}

console.log(arrayIncludes([1,2], 2));
console.log(arrayIncludes([1,2], 5));
© www.soinside.com 2019 - 2024. All rights reserved.