我需要什么
- 我需要将前 3 个元素存储在数组中。
- 并从数组中删除前三个元素。
- 当数组1中第4个元素加起来被删除时,第5个元素加起来2被删除。
最大数组限制为 3。
喜欢arr[1,2,3];
当插入第 4 个元素时,它会删除 arr[1] 索引等。
并将数组存储在cookie中
js代码
var cookie_event_id=document.getElementById("eventID").value;
var e = $(window).height();
var arr=[];
if (cookie.get("event_id")) {
var t=cookie_event_id;
var t = cookie.get("event_id");
console.log(arr.toString());
arr.push(cookie_event_id);
arr.shift();
alert(cookie_event_id);
var i = new Date;
i.setDate(i.getFullYear() ), document.cookie = "event_id =" + cookie_event_id + ";expires=" + i.toUTCString() + ";domain=.10times.com;path=/"
} else
{
var t=cookie_event_id;
var i = new Date;
i.setDate(i.getFullYear() ), document.cookie = "event_id =" + t + ";expires=" + i.toUTCString() + ";domain=.10times.com;path=/"
}
我希望将 id 附加到数组中,然后将该数组推送到 cookie 中。
并在新元素加入时删除数组的第一个索引,依此类推。
数组的最大限制是 3。
最佳答案
如果你想在数组的开头添加新元素:
使用 unshift
:
var arr = [1, 2, 3];
arr.unshift(4); // [4, 1, 2, 3]
arr.length = 3; // [4, 1, 2]
The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.
文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift
如果你想在最后添加元素:
使用 push
和 shift
:
var arr = [1, 2, 3];
arr.push(4); // [1, 2, 3, 4]
arr.shift(); // [2, 3, 4]
推送
:
The push() method adds one or more elements to the end of an array and returns the new length of the array.
文档:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/push
转变
:
The shift() method removes the first element from an array and returns that element. This method changes the length of the array.
文档:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/shift
关于javascript - 如何在javascript中添加数组中的前三个元素并删除之前的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30258935/