Javascript 查找数组的值?
我正在编写一个音序器,它可以让你选择你想要的声音被带入代码的不同部分。我使用的数组保存声音ID值,如果选择了不同的声音,则会重置数组并更改值。起初,我认为使用这个片段可以检查选择了什么声音:Javascript 查找数组的值?,javascript,arrays,list,if-statement,Javascript,Arrays,List,If Statement,我正在编写一个音序器,它可以让你选择你想要的声音被带入代码的不同部分。我使用的数组保存声音ID值,如果选择了不同的声音,则会重置数组并更改值。起初,我认为使用这个片段可以检查选择了什么声音: if(sounds == 1){ //insert effect of sound value } 但是,这没有任何作用。然后我试着: sounds == [1]; 但这根本没有效果。当试图基于单个项目的数组值执行代码时(如果有意义的话),应该使用什么代码?据我所知,您想检
if(sounds == 1){
//insert effect of sound value
}
但是,这没有任何作用。然后我试着:
sounds == [1];
但这根本没有效果。当试图基于单个项目的数组值执行代码时(如果有意义的话),应该使用什么代码?据我所知,您想检查数组中的值,对吗? 这样,您可以使用
includes()
方法检查数组的值
比如:
这可能会解决您的问题。基于我们的问题,您说您有一个声音值数组。我想它看起来像
var sounds=[“1”]
如果是这种情况,您可以执行
声音。包括(“1”)
以查看它“1”
是否存在。首先,通过写入声音==1
检查“声音”数组的大小是否为1
要访问数组元素本身的值,请使用:
sounds[0] == n
数组中的计数从0开始,最后一个元素将是数组的长度sounds.length-1
现在,如果我正确理解了您的问题本身,并且您希望根据从数组中选择的元素输出某些声音,那么您可以使用Switch/Case。首先使用for
循环遍历数组。然后声明Switch()
表达式。然后,写下发生case
时应该发生什么样的输出/操作
for (int i = 0; i < values.length; i++) {
Switch (sounds[i]) {
case 1: // imagine sound ID is 1
//output code // this code will get executed
break;
case 2: // sound ID is 2
//output code // this code will get executed
break;
case 3: // sound ID is 2
//output code // this code will get executed
break;
}
}
for(int i=0;i
试试,听起来像[0]
。这只是指数组的长度
-不,不是。。。如果sounds
是一个数组,那么您基本上是在测试一个对象是否==1—它永远不会。。。。还有,该代码中的code>是一个语法错误sounds==[1]
将发出的任何声音与具有单个元素(1)的数组进行比较,然后忽略结果-这基本上是一条不执行任何操作的行
for (int i = 0; i < values.length; i++) {
Switch (sounds[i]) {
case 1: // imagine sound ID is 1
//output code // this code will get executed
break;
case 2: // sound ID is 2
//output code // this code will get executed
break;
case 3: // sound ID is 2
//output code // this code will get executed
break;
}
}