点名: 每次刷新网页运行, 在控制台 随机输出一位同学的名字 ["老赵", "老李", "小传", "小黑"],如果输出了,则数组中删除javasctiptrtipt
时间: 2024-06-03 16:05:40 浏览: 16
点名是一种在控制台随机输出数组中同学名字的程序。可以通过以下JavaScript代码实现:
```
var names = ["老赵", "老李", "小传", "小黑"];
function pickName() {
if (names.length > 0) {
var index = Math.floor(Math.random() * names.length);
console.log(names[index]);
names.splice(index, 1);
} else {
console.log("所有同学都已经点名完毕!");
}
}
pickName();
```
相关问题
java中点名: 每次刷新网页运行, 在控制台 随机输出一位同学的名字 ["老赵", "老李", "小传", "小黑"],如果输出了,则数组中删除这个名字
在Java中实现该功能可以使用Random类来生成随机数,再使用数组来存储同学的名字,从而达到随机输出的效果。
以下是示例代码:
```
import java.util.Random;
public class RollCall {
public static void main(String[] args) {
String[] names = {"老赵", "老李", "小传", "小黑"};
Random random = new Random();
int index = random.nextInt(names.length); // 生成随机数
System.out.println(names[index]); // 输出随机点名的同学名字
// 删除已经点名的同学名字
String[] newNames = new String[names.length-1];
for (int i=0, j=0; i<names.length; i++) {
if (i != index) {
newNames[j++] = names[i];
}
}
names = newNames;
}
}
```
现在需要制作一个点名系统,每次刷新网页, 随机输出一位同学的全部信息。每位同学都为一个对象,编写递归函数以初始化对象实例。提示:随机数通过Math.random()生成。(50分)
以下是可能的解决方案:
先定义一个Student对象:
```javascript
function Student(name, age, gender, grade) {
this.name = name;
this.age = age;
this.gender = gender;
this.grade = grade;
}
```
然后定义一个数组,存储所有学生的信息:
```javascript
var students = [
new Student("张三", 18, "男", "一年级"),
new Student("李四", 17, "女", "二年级"),
new Student("王五", 16, "男", "三年级"),
new Student("赵六", 15, "女", "四年级"),
new Student("钱七", 14, "男", "五年级")
];
```
最后定义递归函数,初始化每个学生对象:
```javascript
function initStudents(students, index) {
if (index == students.length) return;
students[index].id = index + 1;
initStudents(students, index + 1);
}
initStudents(students, 0);
```
这个函数会递归调用自己,直到初始化完所有学生对象。
最后,可以用以下代码随机输出一个学生的信息:
```javascript
var randomIndex = Math.floor(Math.random() * students.length);
var randomStudent = students[randomIndex];
console.log(randomStudent);
```
这个代码会生成一个随机数(0 ~ 学生数量-1),然后用这个随机数获取对应的学生对象,最后输出这个对象的信息。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![html](https://img-home.csdnimg.cn/images/20210720083451.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)