访问多维数组的第n个元素

访问多维数组的第n个元素

我正在引用以下代码,但是在访问多维数组的第n个元素时遇到困难。请参见以下代码,以获取最低限度的工作示例,最后一个console.log在我希望其返回1时返回“ undefined”。



var intervaldefinitions = [
    [0,  "Unison", "Unison"],
    [1,  "m2",     "minor second"],
    [2,  "M2",     "Major second"],
    [3,  "m3",     "minor third"],
    [4,  "M3",     "Major third"],
    [5,  "P4",     "Perfect fourth"],
    [6,  "TT",     "Tritone"],
    [7,  "P5",     "Perfect Fifth"],
    [8,  "m6",     "minor sixth"],
    [9,  "M6",     "Major sixth"],
    [10, "m7",     "minor seventh"],
    [11, "M7",     "Major seventh"],
    [12, "Octave", "Octave"]
];

function intervalnametonumber(interval)
{
     var i = 0;
     for(i = 0; i < 13; i++)
     {
         if(intervaldefinitions[i][2] === interval)
              var intervalnumber = intervaldefinitions[i][0];
              return intervalnumber;
     }
}

console.log(intervalnametonumber("Unison"))
//Returns 0

console.log(intervalnametonumber("minor second"))
//Returns undefined, whereas I would expect it to return 1

最佳答案

if语句中有2行代码,因此需要将其包装在{}中。如果是单行,则{}是可选的。

所以-

if(intervaldefinitions[i][2] === interval) {
  var intervalnumber = intervaldefinitions[i][0];
  return intervalnumber;
}


要么

if(intervaldefinitions[i][2] === interval)
  return intervaldefinitions[i][0];


工作守则-



  var intervaldefinitions = [
  [0, "Unison", "Unison"],
  [1, "m2", "minor second"],
  [2, "M2", "Major second"],
  [3, "m3", "minor third"],
  [4, "M3", "Major third"],
  [5, "P4", "Perfect fourth"],
  [6, "TT", "Tritone"],
  [7, "P5", "Perfect Fifth"],
  [8, "m6", "minor sixth"],
  [9, "M6", "Major sixth"],
  [10, "m7", "minor seventh"],
  [11, "M7", "Major seventh"],
  [12, "Octave", "Octave"]];

function intervalnametonumber(interval)
{
     for(var i=0; i<13;i++) {
       // console.log(intervaldefinitions[i][2])
         if(intervaldefinitions[i][2] === interval) {
              var intervalnumber = intervaldefinitions[i][0];
              return intervalnumber;
         }
     }
}

console.log(intervalnametonumber("Unison"))

//Returns 0

console.log(intervalnametonumber("minor second"))

//Returns undefined, whereas I would expect it to return 1

10-06 00:39