javascript - 从单击事件中调用外部函数并将参数作为数组传递给它

标签 javascript jquery

$(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>

我尝试根据解决方案数组中包含的数组来检查一个数组(获取),该数组填充了从表中的点击中派生的值。为此,我使用一个完成这项工作的参数进行了函数检查。数组taken作为参数传递给函数,并通过方法push填充可用值。

范围似乎很好,因为如果我使用满足解决方案之一的值初始化“taken”,则函数“check”的返回值为 true。 但是将push方法应用到变量taken返回总是未定义的,所以看起来全局taken没有填充push或者类型不同?。

最佳答案

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

关于javascript - 从单击事件中调用外部函数并将参数作为数组传递给它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42901309/

相关文章:

javascript - 为什么引用全局对象的局部变量似乎违反了函数作用域?

javascript - 如何基于 api 调用遍历树/数组 -Javascript

JavaScript 小数增量?

javascript - Parsefloat 总是返回 NaN

javascript - 使用数据属性在 javascript (jQuery) 中检索对象键的值

javascript - CSS - 固定菜单按钮在滚动时显示

javascript - 页面加载后加载脚本?

javascript - 如何在 HTML 页面中显示图像

javascript - JQuery 中点击事件的链接函数 : Creating . post 变量

javascript - 将类放到具有等效 href 的链接中