简体   繁体   中英

Calling a external function from within a click event and passing it an argument as array

 $(document).ready(function(){ var available=["1","2","3","4"]; var taken=[]; var solutions=[["1","2"],["3","4"]]; // external function function check(input){ for(var i=0;i<solutions.length;i++){ var result=solutions[i].every(function(elem){ return input.includes(elem)==true; }) if(result==true){ return result; } } } // click event $("table td").click(function(){ debugger var removed=available.splice(available.indexOf(this.id),1); taken.push(removed); check(taken); // the call works if the array *taken* is initialize //by hand, but doesn't work filling the array with //the push method as always return an undefined value }) }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table style="width:100%"> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> </tr> <tr> <td>Jill</td> <td>Smith</td> <td>50</td> </tr> <tr> <td>Eve</td> <td>Jackson</td> <td>94</td> </tr> </table> 

I try to check an array ( taken ) filled with values derived from clicks in a table against arrays contained in the solution array. For that I made a function check with one parameter that does that job.The array taken is passed as argument to the function and is filled with available values through the method push.

The scopes seem that are well because if I initialize taken with values that met one of the solutions the return of the function check is true. But applying the push method to variable taken the return is always undefined, so it seems that the global taken is not filled with push or the types are different?.

我发现available.splice(available.indexOf(this.id),1)返回的对象不是字符串,因此我需要使用toString()将其转换为字符串,以使taked数组成为字符串数组,而不是对象数组。

There is no issue with the function call , please check your external function either it should return true or false as per your code its only return in one scenario. try with this function --

function check(input){
for(var i=0;i<solutions.length;i++){
var result = false;
    result=solutions[i].every(function(elem){
          return input.includes(elem)==true;
   })
      return result;
    }

}

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