简体   繁体   中英

convert jquery each function to pure javascript

I have script to show dropdown in select box. The script currently i am using is

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);

    });
});

How can i convert this to pure javascript. Because if i am using this

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);

    });
});

it is not working.

Note the difference in order of arguments in native forEach - first is the value of item, second is index. So instead of:

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

use this:

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

Your method signature is wrong. It's:

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

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

You are using the .forEach() method wrong. forEach docs

You don't need to pass the array in as first argument. Just pass the callback.

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

or with key / value iteration

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

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