最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to add new elements to an array without overwriting the first one? - Stack Overflow

programmeradmin3浏览0评论

I'm trying to add new elements to an Array but it keeps overwriting it the first element, i'm not sure if i'm doing it correctly, but this is my code:

//name and age contains value from a NgModel 
this.data = [
    { "name": this.name, "age": this.age },
];

//Adds them to a new array 
this.nArray = [];
this.nArray.push(this.data);

I'm trying to add new elements to an Array but it keeps overwriting it the first element, i'm not sure if i'm doing it correctly, but this is my code:

//name and age contains value from a NgModel 
this.data = [
    { "name": this.name, "age": this.age },
];

//Adds them to a new array 
this.nArray = [];
this.nArray.push(this.data);
Share Improve this question edited Jun 27, 2018 at 19:07 vahdet 6,74910 gold badges61 silver badges114 bronze badges asked Jun 27, 2018 at 18:53 QuickAccount123QuickAccount123 1891 gold badge5 silver badges15 bronze badges 6
  • Is this in its own method? Are you creating a new [] each time this method is called?. Hence only pushing one item into it each time. – Jimenemex Commented Jun 27, 2018 at 19:13
  • Could you add more context? – V. Sambor Commented Jun 27, 2018 at 19:20
  • @V.Sambor What i'm trying to do is keep adding new elements based on this.data(which contains name and age from an NgModel) – QuickAccount123 Commented Jun 27, 2018 at 19:22
  • how do you 'keep adding'? In the code you have provided, you add only once. Show us the entire function at least. – V. Sambor Commented Jun 27, 2018 at 19:23
  • @V.Sambor I think that's the problem how to add it more than once – QuickAccount123 Commented Jun 27, 2018 at 19:50
 |  Show 1 more ment

6 Answers 6

Reset to default 5

Use concat when you want to merge two arrays.

const nArray = [];
const arr = nArray.concat(this.data);

You can now use the new merged array for your purpose

As it is, you are pushing an array to an empty array. So, there is nothing like overriding here. However, assuming this.nArray is filled with some elements already, you should use the spread syntax for concatenating two arrays like:

this.nArray.push(...this.data);

push method is ok for you. It will add elements at the end of the array. If you have data already setted in your array, then remove this.nArray = [] because this is creating a new empty array, deleting all previous data stored in nArray variable. In any case, if you want to add elements at the beginning try unshift: this.nArray.unshift(this.data);.

If you push data inside nArray you will get an array of array of objects. Maybe you are looking to add only the elements in data and not the whole array. Use concat method for that.

this.nArray.push(this.nArray.concat(data));

Or a shorten syntax using spread operator ...: this.nArray.push(...data);

NOTE: I'd remend you to use const for your array definition and remove the blank assignment of [] in nArray. Also, instead of using concat, use the spread operators with the push method.

Another way to add/insert an element into an array is to use the .splice() method.

With .splice() you can insert a new element at any given index, either overwriting what is currently in that index number, or inserting within, with no overwriting.

Example:

let secretMessage = [ 'Programming', 'is', 'not', 'about', 'what', 'you', 'get', 
'easily', 'the', 'first', 'time,', 'it', 'is', 'about', 'what', 'you', 'can',
'figure', 'out.', '-2015,', 'Chris', 'Pine,', 'Learn', 'to', 'Program' ]

read: 'Programming is not about what you get easily the first time, it is about what you can figure out. -2015, Chris Pine, Learn to Program'

secretMessage.splice(6, 5, 'know,');

console.log(secretMessage.join(' '); //log array elements to console, but join them 
                                    //with a space (makes it more human legible)

read: 'Programming is not about what you know, it is about what you can figure out. -2015, Chris Pine, Learn to Program'

In this example, at index (position) 6 (starting from 0) we replace the 5 elements from index 6 with the third argument - 'know,'.

If you wanted to insert an element without replacing another, use the same .splice() method but for the second argument, type 0.

Example:

let favDrink = ['I', 'like', 'milkshake.']

favDrink.splice(2, 0, 'banana'); //at index position 2, insert 'banana'. 
                                 //***Does not replace 'milkshake'***

console.log(favDrink.join(' ');

read: 'I like banana milkshake.'

Source: https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

You know what? You might be reinitializing your array every time.

Try something like this:

// create your new array 
this.nArray = [];
// other code
// loop, etc
$.each(row, function(index, data) {
  this.data = [
    { "name": this.name, "age": this.age },
  ];
  // now add this element to your array:
  this.nArray.push(this.data);
};

Adding the Object in the array...! Write in this format

let data = [];

data[data.length] = {name:"Aarti",age:22}


data[data.length] = {name:"Saurav",age:23}

console.log(data);
发布评论

评论列表(0)

  1. 暂无评论