【问题标题】:How to add the value from an input box to an array and then output its contents?如何将输入框中的值添加到数组中,然后输出其内容?
【发布时间】:2020-04-26 23:59:29
【问题描述】:

如何将输入框的值添加到数组中,然后显示该数组的内容? 这就是我想出的,但我不确定它为什么不起作用 - console.log 也不会向控制台发布任何内容。

var user = user;
if (!user) {
  user = prompt('Please choose a username:');
  if (!user) {
    alert('Your name has been set to "Anonymous"');
  } else {
      alert('Your name has been set to "'+ user +'"');
  }
}

var items = [];
function userArray() {
    items.push(user);
    return false;
    console.log(items);
    }

socket.on('onlineUsers', function (data) {
      $('.dispUser').html(items);
    });

文件中的其余代码如下,以防万一……(根据第一个答案更改了返回语句)

var user = user;
if (!user) {
  user = prompt('Please choose a username:');
  if (!user) {
    alert('Your name has been set to "Anonymous"');
  } else {
      alert('Your name has been set to "'+ user +'"');
  } 
}

var items = [];

function userArray() {
    items.push(users);
    console.log(items);
    return false;
    }

socket.on('onlineUsers', function (data) {
      $('.dispUser').html(items);
    });

//Counts the number of users online
socket.on('count', function (data) {
  $('.user-count').html(data);
});

//Receives messages and outputs it to the chat section
socket.on('message', function (data) {
  $('.chat').append('<p><strong>' + data.user + '</strong>: ' + data.message + '</p>');
  $('.chat').scrollTop($('.chat').height());
});


//SENDING OF THE MESSAGE
//Submit the form through HTTPS
$('form').submit(function (e) {
  e.preventDefault();

  // Retrieve the message from the user
  var message = $(e.target).find('input').val();

  // Send the message to the server
  socket.emit('message', {
    user: user || 'Anonymous',
    message: message
  });

  // Clears the message box after the message has been sent
  e.target.reset();
  $(e.target).find('input').focus();
});

【问题讨论】:

    标签: javascript html node.js express socket.io


    【解决方案1】:

    回答

    您的实现很好,但是您有一个错误,导致它无法按照您的描述工作。

    console.log(items) 的调用不会打印任何内容,因为那行代码永远不会运行。

    从函数返回时,不会运行后续代码行。您应该将 return 作为函数中的最后一行,或者将其包装在条件中。

    例如:

    function userArray() {
      items.push(user);
      console.log(items);
      return false;
    }
    

    如何调试

    学习自己解决这个问题的技巧是一个非常宝贵的工具。您可以利用调试器(例如 Chrome Devtools)向代码添加断点。这些将允许您在特定的行上停止执行,查看变量的值,并单步执行剩余的代码行。

    这样做可以清楚地看到代码行永远不会运行。

    在此处了解更多详情:https://developers.google.com/web/tools/chrome-devtools/javascript

    【讨论】:

    • 这是一个我不知道的 Chrome 小技巧 - 谢谢。确实,该函数没有运行,所以现在我必须找出原因。
    • 好吧,那是因为你没有调用它。就像您调用各种 promptalertArray#pushConsole#log 函数一样,它们被声明为 Javascript 语言的一部分;您将需要调用您定义的userArray 函数。你会想要这样的东西:userArray().
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多