是否可以在数组中使用x?

问题描述 投票:0回答:2

确定,这个想法是将x用作数组编号,这样我就可以计数并打印一系列内容,并同时输入内容。

目标是在数组[]中加x,然后保存定义的变量并立即打印出来。

我不会认为自己是优秀的程序员,而只是加入其中。任何人都可以帮我解决这个问题,因为以下代码不起作用,就我所知而言,这可能只是语法错误!

try {
  var m;
  var b[5];
  for (var x = 0; x < 5; x++) {
    switch (b[x]) {
      case 0:
        b[x] = "bock ";
      case 1:
        b[x] = "look ";
        break;
      case 2:
        b[x] = "boke ";
        break;
      case 3:
        b[x] = "alle ";
        break;
      case 4:
        b[x] = "pore ";
        break;
      case 5:
        b[x] = "goet ";
        break;
    }
    document.write(b[x]);
  }
}
catch (err) {
  document.write("an error has occurred.<br>" + err);
}
javascript html variables switch-statement try-catch
2个回答
0
投票

这是您要实现的目标

var b = [];

try {
    for (var x = 0; x < 5; x++) {
        switch (x) {
            case 0:
                b[x] = "bock ";
            case 1:
                b[x] = "look ";
                break;
            case 2:
                b[x] = "boke ";
                break;
            case 3:
                b[x] = "alle ";
                break;
            case 4:
                b[x] = "pore ";
                break;
            case 5:
                b[x] = "goet ";
                break;
        }
        console.log(b[x]);
    }
} catch (err) {
    console.log("an error has occurred.<br>" + err);
}

0
投票

注意:

  1. [var b = []而不是var b = [5]

  2. [switch(x) {而不是switch(b[x])

var m;  
  var b = [];
  for(var x = 0; x < 5; x++) {
      switch(x) { 
        case 0: 
          b[0] = "bock "; 
        case 1:
          b[1] = "look ";
          break; 
        case 2: 
          b[2] = "boke ";
          break;
        case 3:
          b[3] = "alle "; 
          break;
        case 4:
          b[4] = "pore ";
          break;
        case 5: 
          b[5] = "goet "; 
        break; 
    }
}

  console.log(b);
© www.soinside.com 2019 - 2024. All rights reserved.