在js中,随机数组的索引,便可以获得数组随机的值。下面小编举例讲解js怎样从数组中随意取一个值。
工具/原料
1
联想笔记本Air14
2
操作系统Windows 10
3
zend studio10.0
方法/步骤
1
新建一个html文件,命名为test.html,用于讲解js怎样从数组中随意取一个值。
2
在script标签内,创建randindex函数,其中arr为数组参数。
3
在randindex函数内,通过Math对象的random()方法获得随机数,并使用floor()方法进行取整,从而获得随机的数组索引值,使用return将数组索引返回。
4
在script标签内,创建一个数组arr用于测试,并调用randindex函数获得随机索引i。
5
在script标签内,通过索引i获得数组的值,使用write()方法将随机的数组值输出。
6
在浏览器打开test.html文件,查看结果。
总结:
1、在script标签内,创建randindex函数,其中arr为数组参数。 2、在randindex函数内,通过Math对象的random()方法获得随机数,并使用floor()方法进行取整,从而获得随机的数组索引值,使用return将数组索引返回。 3、在script标签内,通过索引i获得数组的值,使用write()方法将随机的数组值输出。 4、在浏览器打开test.html文件,查看结果。