【问题标题】:Finding the value of an array?查找数组的值?
【发布时间】:2020-04-15 01:22:27
【问题描述】:

我正在编写一个音序器,它允许您选择要将哪种声音带入代码的不同部分。我正在使用一个包含声音 ID 值的数组,如果选择了不同的声音,则数组会被重置并且值会发生变化。最初,我认为使用这个 sn-p 可以检查选择了什么声音:

    if(sounds == 1){
    //insert effect of sound value
    }

但是,这并没有起到任何作用。然后我尝试了:

   sounds == [1];

但这根本没有效果。尝试根据具有单个项目的数组的值执行代码时应该使用什么代码(如果有意义的话)?

【问题讨论】:

  • 试试,sounds[0] ..
  • this only ends up referring to the length of the array - 不,它不是......如果sounds 是一个数组,你基本上是在测试一个对象是否== 1 - 它永远不会......还有,该代码中的; 是语法错误
  • sounds == [1];sounds 与具有单个元素 (1) 的数组进行比较,然后忽略结果 - 它基本上是无所事事的行

标签: javascript arrays list if-statement


【解决方案1】:

据我了解您的担忧,您想检查数组中的值对吗? 这样,您可以使用includes() 方法检查数组的值。

喜欢:

sounds = [1,2,3,4,5,6];

if(sounds.includes(1)) {
   //insert effect of sound value
} else {
   // Do else thing here.
}

这可能会解决您的问题。

【讨论】:

    【解决方案2】:

    首先,通过编写sounds == 1,您正在检查“sounds”数组的size 是否为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;
       }
    }
    

    【讨论】:

      【解决方案3】:

      根据我们的问题,您是说您有一组声音值。我想它看起来像

      var sounds = ["1"]

      如果是这种情况,您可以通过sounds.includes("1") 来查看"1" 是否存在。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-28
        • 2020-09-06
        相关资源
        最近更新 更多