[英]How to empty a array after it has specific number of elements?
I am trying to keep a watch on a array , and when it has 10 elements in it , I want to clear the array. 我正在尝试监视一个数组,当其中有10个元素时,我想清除该数组。 I tried using proxies but I am not able to clear my array.
我尝试使用代理,但无法清除阵列。 What I am trying to achieve is that, I am trying to push some data into an array from eventlisteners , and when the array length reaches 10 I want to send the data to server and clear the array.
我想要实现的是,我试图将一些数据从eventlisteners推入数组,并且当数组长度达到10时,我想将数据发送到服务器并清除数组。
You can do it by overriding push method of the array, 您可以通过重写数组的push方法来做到这一点,
function getArrayWithLimitedLength(length) {
var array = new Array();
array.push = function () {
if (this.length >= length) {
this.splice(0,this.length)
}
return Array.prototype.push.apply(this,arguments);
}
return array;
}
Create an array with length 3 创建一个长度为3的数组
var array = getArrayWithLimitedLength(3);
once You add 4th element previous 3 elements will be removed and last element will be added as first element. 一旦您添加了第4个元素,前面的3个元素将被删除,最后一个元素将被添加为第一个元素。
You can use this.splice(0,this.length)
, this.length = 0
to clear the array 您可以使用
this.splice(0,this.length)
, this.length = 0
清除数组
or 要么
while(this.length > 0) {
this.pop();
}
Example: 例:
array.push(1) // array-> [1]
array.push(2) // array-> [1,2]
array.push(3) // array-> [1,2,3]
array.push(4) // array-> [4]
You could check if the array has 10 elements and then call a function for sending the array. 您可以检查数组是否包含10个元素,然后调用函数以发送数组。 Then empty the array by seting the length to zero.
然后通过将长度设置为零来清空数组。
function sendArray(array) { console.log(...array); } var array = []; setInterval((i => () => { array.push(i++); if (array.length === 10) { sendArray(array); array.length = 0; } })(0), 100);
Implement you own myPush
method: 实现您自己的
myPush
方法:
Array.prototype.myPush = function(element, maxLengthBeforeFlush= Infinity) { this.push(element); if (this.length > maxLengthBeforeFlush) { // code to send this to the server this.length = 0; } } var arr = [];
<button type="button" id="pushToArr" onclick="arr.myPush('a', 5); console.log(arr);">Click to push to arr[]</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.