javascript显示数组中的用户定义元素

时间:2015-06-03 10:08:29

标签: javascript html arrays json

我需要制作一个简单的javascript代码来显示包含5个元素的水果数组中的元素,但条件是水果必须是用户定义的水果索引必须是用户提供的并且javascript才能打印出来。

文本区域必须是用户输入,在提交时它会显示元素

1 个答案:

答案 0 :(得分:1)

有很多方法可以做到这一点,也许最简单的方法是使用提示框。

var fruits = ["fruit1", "fruit2", "fruit3", "fruit4"];

var choice = prompt("Please enter a number between 0 and " + fruits.length);

// check that it is not null
if(choice)
{
  //convert to an integer
  parseInt(choice);
  alert(fruits[choice]);
  //or
  console.log(fruits[choice])
}

显然你应该对字符串进行验证,以确保它是一个整数!