Javascript js数组观察更改,然后循环推送操作
我已经实现了一个函数,而数组推送操作符执行某些操作Javascript js数组观察更改,然后循环推送操作,javascript,typescript,Javascript,Typescript,我已经实现了一个函数,而数组推送操作符执行某些操作 如下所示:当推送数据时,它将调用refreshView一次; 但当循环100次推送操作时,它将调用refreshView100次 在完成循环时调用最后一个refreshView()有什么想法吗 var arr=[]; arr.push=函数(){ Array.prototype.push.apply(这是参数); 刷新视图(); } 函数refreshView(){ //执行一些操作 } arr.push(1);//它将调用refresh
如下所示:当推送数据时,它将调用
refreshView
一次;
但当循环100次推送操作时,它将调用refreshView
100次
在完成循环时调用最后一个
refreshView()
有什么想法吗
var arr=[];
arr.push=函数(){
Array.prototype.push.apply(这是参数);
刷新视图();
}
函数refreshView(){
//执行一些操作
}
arr.push(1);//它将调用refreshView()1次;
对于(变量i=0;i<100;i++){
arr.push(i);//它将调用refreshView()100次,循环完成后如何调用refreshView()。。
}
最好的选择是使用超时来延迟函数调用,因此只能在完成时运行:
var arr = [];
var timer;
arr.push = function () {
Array.prototype.push.apply(this, arguments);
if(timer)
{
clearTimeout(timer);
)
timer = setTimeout(refreshView, 10);
}
function refreshView() {
// perform some operations
}
arr.push(1); // it will call refreshView() 1 times;
for (var i = 0; i < 100; i++) {
arr.push(i); // it will call refreshView() 100 times, how can i call refreshView() once after loop finish..
}
var arr=[];
无功定时器;
arr.push=函数(){
Array.prototype.push.apply(这是参数);
中频(定时器)
{
清除超时(计时器);
)
定时器=设置超时(刷新视图,10);
}
函数refreshView(){
//执行一些操作
}
arr.push(1);//它将调用refreshView()1次;
对于(变量i=0;i<100;i++){
arr.push(i);//它将调用refreshView()100次,循环完成后如何调用refreshView()。。
}
不知道你在问什么。只需在循环后显式调用notifyDataChange()
即可。请尝试在for内的arr.push(i);
之后添加if(i==99){notifyDataChange();}
loop@Sam0否,它将调用一次refreshView的每个推送操作符。@RobbyCornelissen notifyDataChange()只需更改refreshView(),您能理解吗?所以您不希望每次推送时都执行refreshView()
?那么为什么要将它放在push()
方法中?