javascript - 无法获取数组的值
问题描述
仍然无法理解我对这段代码的错误。所有我想要的 - 通过提示获取所有用户列表(姓名/姓氏)
function UserList() {
let users = [];
while (true) {
let response = prompt('Please, enter your name surname?');
if (response == null) {
alert('cancel');
break;
}
users.push(response.split(' '));
}
return users;
}
function User() {
this.name = userList[0];
this.surname = userList[1];
this.regDate = new Date;
for (i = 0; i < userList.length; ++i) {
console.log('Name: ' + this.name + ' Surname: ' + this.surname + '. Date of registration : ' + this.regDate)
}
}
let userList = new UserList();
let user = new User();
而且我遇到了一个误解,为什么尽管我输入了 users.push (response.split(' ')) ,但我无法得到第一个提示词。userList [0] - 显示数组的第一个索引而不是第一个单词。
其次,我想在 console.log 中获取所有用户列表,但我得到的是相同的字符串,具体取决于数组的长度
解决方案
函数 User 中的 userList[0] 将返回一个数组:['name', 'surname']。例如,要获取名字,您需要使用 this.name = userList[i][0]
function UserList() {
let users = [];
while (true) {
let response = prompt('Please, enter your name surname?');
if (response == null) {
alert('cancel');
break;
}
users.push(response.split(' '));
}
return users;
}
function User() {
for (var i = 0; i < userList.length; ++i) {
this.name = userList[i][0];
this.surname = userList[i][1];
this.regDate = new Date;
console.log('Name: ' + this.name + ' Surname: ' + this.surname + '. Date of registration : ' + this.regDate)
}
}
let userList = new UserList();
let user = new User();
推荐阅读
- java - 如何解决 Jenkins This site can't bereached localhost denied to connect 错误?
- reactjs - 使用 React AsyncSelect 的 React Hook Form 无法加载选项
- android - Android 位置之间的距离,结果意味着什么
- java - 测量各种微服务的 2 个点之间的时间
- git - When creating new branch, How to extend branch name from the existing branch (include example)
- python - 如何根据字符串熊猫数据框列中的每个值附加特定字符串?
- plot - 在 MOSI 引脚上绘制数据
- c# - 寻找最佳实践 - C# - 将文件读取到对象,编辑并保存回 - 不是 XML,Json
- testing - Testcafe 不能与 Yarn 2 一起运行
- php - 为 css 和 js 文件名添加时间 - 它是如何工作的