【问题标题】:Is it posible to push an array into a queue or stack in Javascript?是否可以在 Javascript 中将数组推送到队列或堆栈中?
【发布时间】:2016-06-27 16:30:24
【问题描述】:

我知道我可以将整数或字符放入队列或堆栈中,但是推送整个数组怎么样?

var stack = [];
stack.push(2);       // stack is now [2]
stack.push(5);       // stack is now [2, 5]
var i = stack.pop(); // stack is now [2]
alert(i);            // displays 5

var queue = [];
queue.push(2);         // queue is now [2]
queue.push(5);         // queue is now [2, 5]
var i = queue.shift(); // queue is now [5]
alert(i);              // displays 2

假设我有数据从客户端发送到服务器,服务器需要存储它们以便以后发布它们。我正在发送三个字段,usernamemessageavatar

例子:

['simon','this is a message','avatar.png']

['Muray','this is another message','avatar2.png']

这两个数组应该被发送到服务器并在需要时弹出整个数组。

【问题讨论】:

  • 问题在哪里?
  • 数组可以包含任何你想要的东西,包括其他数组。
  • 你是在问能不能把数组压入数组?如果是,那么是的,您可以将数组推入数组中。
  • 你已经写过栈的概念了(:请阅读:bennadel.com/blog/…
  • 为什么不在浏览器控制台中尝试一下,看看会发生什么?

标签: javascript arrays queue


【解决方案1】:

是的,您可以在 JavaScript 中将整个数组推入/弹出数组。

例如:

var a = [];
a.push([1, 2, 3, 4]);
a.pop(); // yields [1, 2, 3, 4]

在你的例子中,你会这样做:

var a = [];
a.push(['simon','this is a message','avatar.png']);
a.push(['Muray','this is another message','avatar2.png']);

您也可以一步定义嵌套数组:

var a = [
  ['simon','this is a message','avatar.png'],
  ['Muray','this is another message','avatar2.png']];

如果您要将其发送到服务器,您可能希望使用JSON.stringify 对其进行编码JSON,如下所示:

JSON.stringify(a);

这将产生一个包含

的字符串

[["simon","这是一条消息","avatar.png"],["Muray","这是另一条消息","avatar2.png"]]

【讨论】:

    猜你喜欢
    • 2013-05-26
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 2019-04-26
    • 2013-09-30
    • 2021-03-17
    • 2021-08-25
    • 1970-01-01
    相关资源
    最近更新 更多