Search code examples
javascriptarrays

Shortest way to change multiple values of an array at once?


Perhaps too small question for it's own post...

So basically I'm looking for something like:

myarray[2, 3, 7] = 155, 34, true;

Is there some kind of line like this that works? Or what would be the shortest way to accomplish this, without changing all 3 manually?


Solution

  • If you're looking for something like destructuring assignment, that's not coming until ECMAScript 6, and won't look quite like that.

    To do what you seem to want, you'll just need to assign separately.

    myarray[2] = 155;
    myarray[3] = 34;
    myarray[7] = true;
    

    Or create a function that handles it for you.

    function assign(obj, props, vals) {
        for (var i = 0; i < props.length; i++) {
            obj[props[i]] = vals[i];
        }
    }
    

    And call it like this:

    assign(myarray, [2,3,7], [155,34,true]);