-1

I'm trying to push a number to the end of an array without using the push function.

The array returns [1,2,3,10] but the array.length returns 8. I assume it's counting arr twice and the two numbers in 10 = 8. I don't know why.

function push(array, value){
arr=arr+','+value
return arr.length
}

var arr = [1, 2, 3]
console.log(push(arr, 10)) // expecting 4, get 8
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320

5 Answers5

2

+, when the left-hand side is not a number, will concatenate (possibly involving calling toString on the left-hand side first, like what's happening here). You can assign to the index at the length of the array instead:

function push(array, value) {
  array[array.length] = value;
  return array.length;
}

var arr = [1, 2, 3]
console.log(push(arr, 10))
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
2

var arr = [1,2,3];
arr[arr.length] = 4;
console.log(arr);
greentec
  • 2,130
  • 1
  • 19
  • 16
1

For completeness and because it hasn't been said yet you can also do this via array decomposition.

let array = [1, 2, 3];
array = [...array, 10];
console.log(array); // [1, 2, 3, 10]

Beware that this does write an entirely new array, but on the plus side it is immutable for the same reason!

Bradd
  • 196
  • 10
0

Try running this in dev tools so you can see what exactly is happening. By adding a string to an array, you're converting it your original array to a string.

Not sure what you have against array.push() but I'd recommend using it.

enter image description here

imjared
  • 19,492
  • 4
  • 49
  • 72
0

Your code arr=arr+','+value is actually treating the array as a string. So the array starts as 1,2,3 (5 characters long) and then you add ,10 (3 more characters) to equal 8 characters.

If you really want to concatenate to the array without using JavaScript's built-in push() function, I'd suggest the splice() function as in this answer: How to insert an item into an array at a specific index (JavaScript)?

Jordan Rieger
  • 3,025
  • 3
  • 30
  • 50