简体   繁体   中英

Call Javascript function with Object AND array parameters

I've seen many posts about using Javascripts apply() and ES6 ellipses calls but they only seem to deal with passing arrays and that's it. I'd like to pass an Object and an array.

function myFunction(obj, arr) {
    // Not really doing this but you get the idea
    if (arr.includes(obj)) {
        ;;
    }
}

let theArr = ["bob", "mike", "steve"];
let o = "sally";

myFunction(o, theArr); // How can I do something equivalent to this?

Thanks.

The second argument of apply() is the array of arguments , if you want to pass one object and an array you just have to include those in the array. For example:

 function test(el1, el2){ alert(el1.a); alert(el2); alert(this.b); } test.apply( {b: 4}, //First argument, the new *this* variable [{a:1}, [2, 3]] //Second argument is the list of arguments passed to test() );

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