splice first added object in an array when new element is added in javascript
i am working on splicing the old object ie first added object in an array when new element(object) is added in to it automatically.
this is the sample code i worked on
var sampleArr = [{"id":4,"hostName":"henry"},
{"id":3,"hostName":"jeff"},
{"id":2,"hostName":"mark"},
{"id":1,"hostName":"holder"}];
the above array contains 4 objects when 5 object( {"id":5,"hostName":"punk"}) is added i want to splice first added object ie( {"id":1,"hostName":"holder"}).
here is what i tried in controller
for( var i=0; i<sampleArr.length; i++){
var index = i;
if(sampleArr.length > 4){
sampleArr.splice(index,1,sampleArr[i]);
}
}
but it not working as i expected. please any help me to sought out this!
您可以使用简单的pop()
来取出最后一个元素,并使用push
将新元素添加到数组中!
var sampleArr = [{
"id": 4,
"hostName": "henry"
}, {
"id": 3,
"hostName": "jeff"
}, {
"id": 2,
"hostName": "mark"
}, {
"id": 1,
"hostName": "holder"
}];
sampleArr.pop()
sampleArr.push({
"id": 5,
"hostName": "punk"
})
console.log(sampleArr)
You can use unshift
to add new item in begin of array and use pop
to remove last item in array. Read more here.
Try this:
sampleArr.unshift({"id":5,"hostName":"punk"});
sampleArr.pop();
Hope will helps.
I think OP is asking for FIFO (first in first out operation) , since I don't understand how {"id":1,"hostName":"holder"}
could be first element in below array. But here is what I suggest.
Array.prototype.performFIFO = function(element) { this.push(element); this.shift(); return this; }
var sampleArr = [{"id":4,"hostName":"henry"},
{"id":3,"hostName":"jeff"},
{"id":2,"hostName":"mark"},
{"id":1,"hostName":"holder"}];
sampleArr.performFIFO({"id":5,"hostName":"fifth element"})
console.log(sampleArr)
链接地址: http://www.djcxy.com/p/19374.html
上一篇: 之间的区别