7

I've been told not to use push in my coursework, as we are only allowed to use code we have been taught, which I find ridiculous.

I have written over 200 lines of code incorporating the push function multiple times. Is there a simple code alternative to the push function which I can implement for it?

3
  • 1
    You can do arr[index] = 'something' Commented Nov 5, 2015 at 12:54
  • Or arr[arr.length] = "something else" Commented Nov 5, 2015 at 12:56
  • The algorithm for push is in the language specification (§22.1.3.17). Commented Nov 5, 2015 at 13:01

3 Answers 3

12

Nowadays you can use array destructuring:

let theArray = [1, 2, 3, 4, 5];
theArray = [
  ...theArray,
  6,
];
console.log(theArray);

If you want to push several elements, put them at the end of the array. You can even put elements at the beginning of the array:

let theArray = [1, 2, 3, 4, 5];
theArray = [
  -1,
  0,
  ...theArray,
  6,
  7,
  8,
  9,
  10
];
console.log(theArray);

The doc about it:

MDN Destructuring Assignment

Sign up to request clarification or add additional context in comments.

1 Comment

Be careful, this reassign the variable with a new array.
9

If you need to push element to the next index in the array, use:

var arr = [];
arr[arr.length] = "something";
//output: arr = ["something"]

If you need to add element in specific index use:

var arr = [];
arr[3] = "something";
//output: arr = [undefined,undefined,undefined,"something"]

1 Comment

A more accurate output is [,,,"something"] since the first three members don't exist.
5

The closest equivalent

arr[arr.length] = value; 

2 Comments

push also accepts multiple arguments and increments length (since it's a generic method and works on non–array objects too). It also checks that the lengthened array will have a length < 2^53-1, so it's possible to get a lot closer than that. ;-)
My answer was based on a hopefully easy search/replace on 200 lines of code - though, 200 lines is warming up really

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.