是否有更有效的方法来打开字符串数组的每个元素?

时间:2013-12-01 14:16:23

标签: javascript arrays switch-statement

我有一个像var mya = ["someval1", "someotherval1", "someval2", "someval3"];这样的数组,我有一个函数接收一个属性设置为其中一个名称的对象。

迭代数组是有意义的,并检查每个数组是否可以在数组中找到它,就像在for语句中一样。但是在这种情况下,似乎更有效的方法会使用switch语句,因为数组是静态的,找到属性时的任务取决于找到的属性。

如何使用开关阵列执行此操作?像这样的伪代码:

switch(mya.forEach) { 
    case "someval1": 
        alert("someval1"); 
        break; 
    ... 
    default: 
        alert("default"); 
        break; 
}

但这只召唤一次。

给出的答案都是我已经拥有的代码 - 我想foreach没有更清晰的switch表达式。

3 个答案:

答案 0 :(得分:5)

for( var i=0; i<mya.length; i++ ){
    switch( mya[i]) { 
        case "someval1": 
            alert("someval1"); 
            break; 
        ... 
        default: 
            alert("default"); 
            break; 
    }
}

答案 1 :(得分:1)

因为switch不是foreach

for (var i in mya)
{
    switch (mya[i])
    {
        ...
    }
}

答案 2 :(得分:1)

鉴于您考虑使用forEach我假设您不太关心支持旧浏览器,在这种情况下,使用Array.indexOf()更有意义:

var mya = ["someval1", "someotherval1", "someval2", "someval3"],
    returnedFunctionValue = returnRandomValue();

console.log('Searching for: "' + returnedFunctionValue + '."');

if (mya.indexOf(returnedFunctionValue) > -1) {
    // the value held by the returnedFunctionValue variable is contained in the mya array
    console.log('"' + returnedFunctionValue + '" at array-index: ' + mya.indexOf(returnedFunctionValue));
}
else {
    // the value held by the returnedFunctionValue variable is not contained in the mya array
    console.log('"' + returnedFunctionValue + '" not held in the array');
}

Simple JS Fiddle demo

虽然您可以使用Array.prototype.forEach(在现代浏览器中):

var mya = ["someval1", "someotherval1", "someval2", "someval3"],
    returnedFunctionValue = returnRandomValue();

mya.forEach(function(a, b){
    if (a === returnedFunctionValue) {
        console.log('Found "' + returnedFunctionValue + '" at index ' + b);
    }
});

Simple JS Fiddle demo