我正在尝试获得一个数组来保存10个最新的值,到目前为止它还不能工作。
var messages = new Array(10);
function addmessage(message) {
messages.unshift(message);
messages.length = 10;
}
但是当我尝试显示数组时,我无法让它按顺序显示消息……
我用以下命令显示数组:
$.each(messages, function(key, value) {
if(value != null) {
$("#messages").append(value + "<br>");
}
});
发布于 2012-04-18 14:33:46
var messages = []; //use an array literal instead.
function addmessage(message) {
//unshift loads the new value into the beginning
messages.unshift(message);
//if you want to place it in the end, you can use push()
//messages.push(message);
//if you really want it to remain 10, pop off the last
if(messages.length > 10){
messages.pop();
//and if push()
//messages.shift()
}
}
//loop through and append, "latest" first
$.each(messages, function(key, value) {
if(value != null) {
$("#messages").append(value + "<br>");
}
});
如果您随后使用latest first实时/动态加载消息,则you can use .prepend()
发布于 2012-04-18 15:11:49
在它最简单的形式中,您可以拥有:
messages.push(message);
messages.length > 9 && messages.shift();
这将在末尾添加新消息,并在长度达到10时从前面删除一条消息。
发布于 2012-04-18 14:38:35
Try this solution,也许你想让你的项目按相反的顺序排列?
https://stackoverflow.com/questions/10203967
复制相似问题