Javascript 有没有更有效的方法来打开字符串数组的每个元素?
我有一个数组,比如Javascript 有没有更有效的方法来打开字符串数组的每个元素?,javascript,arrays,switch-statement,Javascript,Arrays,Switch Statement,我有一个数组,比如var mya=[“someval1”、“someotherval1”、“someval2”、“someval3”],我有一个函数,用于接收属性设置为这些名称之一的对象 对数组进行迭代并检查是否可以在数组中找到它是有意义的,就像在for语句中一样。但在这种情况下,似乎更有效的方法应该使用switch语句,因为数组是静态的,并且查找属性时的任务取决于找到的属性 如何使用交换机阵列执行此操作?类似于以下伪代码: switch(mya.forEach) { case "so
var mya=[“someval1”、“someotherval1”、“someval2”、“someval3”]代码>,我有一个函数,用于接收属性设置为这些名称之一的对象
对数组进行迭代并检查是否可以在数组中找到它是有意义的,就像在for
语句中一样。但在这种情况下,似乎更有效的方法应该使用switch
语句,因为数组是静态的,并且查找属性时的任务取决于找到的属性
如何使用交换机阵列执行此操作?类似于以下伪代码:
switch(mya.forEach) {
case "someval1":
alert("someval1");
break;
...
default:
alert("default");
break;
}
但这只需要一次
给出的两个答案都是我已经拥有的代码-我想没有更干净的foreach
公式来描述(var I=0;I),因为开关不是foreach
for( var i=0; i<mya.length; i++ ){
switch( mya[i]) {
case "someval1":
alert("someval1");
break;
...
default:
alert("default");
break;
}
}
for (var i in mya)
{
switch (mya[i])
{
...
}
}
考虑到您考虑使用forEach
,我假设您不太关心支持较旧的浏览器,在这种情况下,使用Array.indexOf()
更有意义:
当然,您可以使用Array.prototype.forEach
(在现代浏览器中):
.Cobra_fast更漂亮,但你的也是正确的,而且是第一个。我会在8分钟内给你。
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');
}
var mya = ["someval1", "someotherval1", "someval2", "someval3"],
returnedFunctionValue = returnRandomValue();
mya.forEach(function(a, b){
if (a === returnedFunctionValue) {
console.log('Found "' + returnedFunctionValue + '" at index ' + b);
}
});