How to add an element to an array without any built in functions


So I have these two questions considering the JavaScript language:

  1. Is there any way to append to an array without using the push() function or any other built in functions in the language?

  2. Is there any way to merge two arrays together without using the concat() function or any other built in functions in the language?

Answer 1:

For the first part you can always use the length property of the array, to add the next element:

a = ['a', 'b', 'c', 'd'];
a[a.length] = 'e'; 

// a is now ["a", "b", "c", "d", "e"]

To do the latter, merge the arrays, without a function you can just loop thru the arrays, should pick the largest one to loop on. But yeah, as the comments state. There's usually not a good reason to do so.

Answer 2:

Here are the alternatives for you:

  1. To add the item to the array without push call:

    arr[arr.length] = value;
  2. To concatenate one array to another without concat call:

    for (var i = 0; i < arr2.length; arr1[arr1.length] = arr2[i++]);

Answer 3:

Not sure if this is what you are looking for or why but arr[arr.length] = 1; is the answer both of your questions.

var myArr = [];
myArr[myArr.length] = 1;
myArr[myArr.length] = 2;
myArr[myArr.length] = 3;

var myArr1 = [...]; // has items;
var myArr2 = [...]; // has items;
var mergedArr = [];

for(var i = 0; i < myArr1.length){
    mergedArr[mergedArr.length] = myArr1[i];

for(var i = 0; i < myArr2.length){
    mergedArr[mergedArr.length] = myArr2[i];

Answer 4:

function pop(arr) {
  let finalVar = arr[arr.length - 1];
  arr.length = arr.length - 1;

  return finalVar;


码神部落- 版权声明 1、本主题所有言论和图片纯属会员个人意见,与码神部落立场无关。

最新回复 (0)
    • 码神部落
        立即登录 立即注册 GitHub登录