1

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?

1
  • Nothing built-in, you'd have to create your own function. Commented Nov 29, 2013 at 22:32

3 Answers 3

1

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]);
Sign up to request clarification or add additional context in comments.

1 Comment

I wanted a single line thing because I need to do this for a large maze of arrays and can't be bothered to come up with some megacomplicated loop to do it all for me. That function seems to work perfectly, thanks!
0

You could also opt to use the splice method like so:

    var myArray = [2, 3, 7];
    var otherArray = [155, 34, true];
      function arrayChanger(firstArray, secondArray){
        var orgLength = firstArray.length;
        for(i = 0; i < orgLength; i++){
        myArray.splice(i, 1, secondArray[i]);
     }
    return myArray;
    };
    arrayChanger(myArray, otherArray);

Here's a JSFiddle that shows this solution in action.

Comments

0

Use destructing to solve your problem

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

Solution Explanation

const myarray = [1,2,3,4,5,6,7,8];

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

console.log(myarray) // [1, 2, 155, 34, 5, 6, 7, true]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.