首页 > 解决方案 > 无法获取数组的值

问题描述

仍然无法理解我对这段代码的错误。所有我想要的 - 通过提示获取所有用户列表(姓名/姓氏)

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 中获取所有用户列表,但我得到的是相同的字符串,具体取决于数组的长度

标签: javascriptarrayssplitconstructor

解决方案


函数 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();

推荐阅读