【问题标题】:convert jquery each function to pure javascript将jquery每个函数转换为纯javascript
【发布时间】:2017-06-28 16:10:35
【问题描述】:

我有脚本可以在选择框中显示下拉菜单。我目前使用的脚本是

jQuery.each( dslr, function( index, dslrgp) {
    var aslrp= dslrgp.aslrp;
    jQuery.each( aslrp, function(index2, pslrp) {
        var found = 0;
        jQuery.each( dropdown, function(index3, dditem) {
            if (dditem.countryname == pslrp.countryname)
            {
                foundit = 1;
            }
        });
        if (foundit == 0)
            dropdown.push(pslrp);

    });
});

如何将其转换为纯 javascript。因为如果我使用这个

dslr.forEach(function( index, dslrgp) {
    var aslrp= dslrgp.aslrp;
    aslrp.forEach(function(index2, pslrp) {
        var found = 0;
        dropdown.forEach(function(index3, dditem) {
            if (dditem.countryname == pslrp.countryname)
            {
                foundit = 1;
            }
        });
        if (foundit == 0)
            dropdown.push(pslrp);

    });
});

它不工作。

【问题讨论】:

  • “它不工作”——定义“不工作”。给出明确的问题陈述。您得到的行为与您期望的行为有何不同?
  • "将 jquery 每个函数转换为纯 JavaScript" — jQuery 纯 JavaScript。想要移除对 jQuery 的依赖是有充分理由的,但不要将 jQuery 误认为是 JavaScript 以外的任何东西。
  • 我已经编辑了我的问题。

标签: javascript


【解决方案1】:

注意原生forEach 中参数顺序的不同——首先是项目的值,其次是索引。所以而不是:

aslrp.forEach(function(index2, pslrp) {
...
dropdown.forEach(function(index3, dditem) {

使用这个:

aslrp.forEach(function(pslrp, index2) {
...
dropdown.forEach(function(dditem,index3) {

【讨论】:

    【解决方案2】:

    您使用的.forEach() 方法错误。 forEach docs

    您不需要将数组作为第一个参数传入。只需传递回调即可。

    dslr.forEach(function(dslrgp) {
      // do something..
    }
    

    或使用键/值迭代

    dslr.forEach(function(value, index) {
      // do something..
    }
    

    【讨论】:

      【解决方案3】:

      您的方法签名错误。它是:

      arr.forEach(function callback(currentValue, index, array) {
          //your iterator
      }[, thisArg]);
      

      https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

      【讨论】:

      • 这里的arr、currentValue和array是什么?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-16
      • 2018-05-26
      • 2012-03-08
      • 2020-07-24
      • 2013-10-22
      • 1970-01-01
      • 2016-07-18
      相关资源
      最近更新 更多