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


Question


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;
}


来源:https://stackoverflow.com/questions/25625991/how-to-add-an-element-to-an-array-without-any-built-in-functions


码神部落- 版权声明 1、本主题所有言论和图片纯属会员个人意见,与码神部落立场无关。
2、本站所有主题由该帖子作者发表,该帖子作者爷依然萧洒码神部落享有帖子相关版权。
3、码神部落管理员和版主有权不事先通知发贴者而删除本文。
4、其他单位或个人使用、转载或引用本文时必须同时征得该帖子作者爷依然萧洒码神部落的同意。
5、帖子作者须承担一切因本文发表而直接或间接导致的民事或刑事法律责任。
6、本帖部分内容转载自其它媒体,但并不代表本站赞同其观点和对其真实性负责。
7、如本帖侵犯到任何版权问题,请立即告知本站,本站将及时予与删除并致以最深的歉意。

最新回复 (0)
    • 码神部落
      2
        立即登录 立即注册 GitHub登录
返回
发新帖
作者最近主题: