我可以在一个变量中有多个值吗?

我可以在一个变量中有多个值吗?

问题描述:

标题为单个变量中可以有多个值吗?"

As the title "Can I have multiple values in a single variable?"

首先,我有以下表格:

<form name="myform">
 <input type="text" name="mytext">
 <input type="button" onClick="clickButton()">
</form>

然后,看看我的脚本.

<script>
function clickButton() {
  var x = document.myform.mytext.value;
  var a = 13;
  var b = 17;
  var c = 19;

  if (x == a) {
    alert('hello');
  } else if (x == b) {
    alert('hello');
  } else if (x == c) {
    alert('hello');
  } else {
    alert('goodbye');
  }
}
</script>

有没有办法使一个变量具有多个值?就像var myvalues=1,2,3;

Is there any way to make one variable with multiple values? Like, var myvalues=1,2,3;

对您问题的正确答案是使用方括号表示法:

The correct response to your question would be to use an array. But from what you're trying to do, Looks like your looking for an object, specifically the bracket notation:

function clickButton() {
  var x = document.myform.mytext.value,
    greetings = {
      "13": "hello",
      "17": "hello",
      "19": "hello"
    }
  alert(greetings[x] || "goodbye");
}

<form name="myform">
  <input type="text" name="mytext">
  <input type="button" onClick="clickButton()" value="greet">
</form>