简体   繁体   中英

How to use indexOf to find function in array

I have an array of functions.

var arrOfFunc = [];

I have script that pushes to the array, a function that redraws a google chart

There can be multiple functions depending on how many graphs i decide to put on the page

var chart = "done";

function drawChart(){ ... } //each draw chart function belongs to its own scope.

arrOfFunc.push(drawChart);

$(window).resize(function(){
   if(chart=="done"){
     chart = "waiting";
     setTimeout(function(){
       for(var i in arrOfFunc ){
         arrOfFunc[i]();
       }
       chart = "done"
     },1000);
});

The problem is i have a refresh button for the grid that reruns the whole function that:

  • makes the api call
  • rerenders the grid with drawChart()
  • than pushes the drawChart() function to arrOfFunc;

How can i check to see if the function already exists inside the array before deciding whether to push it to the arrOfFunc object?

Or does .indexOf() only work for strings.

indexOf identifies the object in the array.

Since Javascript treats all the functions as objects, indexOf should work on functions too.

It's against the fundamentals of JS to make multiple drawChart() functions. You just declare it once and invoke it from any object. The " this " that you should have referred within the function will represent the object that you are invoking it from. You best study the this and scoping in JS. I would suggest you to have a look at this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM