我正在尝试向数组中添加新元素,但它会不断覆盖第一个元素,我不确定自己是否做得正确,但这是我的代码:
//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);
答案 0 :(得分:1)
push
方法适合您。它将在数组的 end 中添加元素。如果您已经在数组中设置了数据,请删除this.nArray = []
,因为这将创建一个新的空数组,并删除存储在nArray
变量中的所有先前数据。无论如何,如果要在开头添加元素,请尝试unshift
:this.nArray.unshift(this.data);
。
如果将data
推入nArray
内,将得到一个对象数组。也许您只想添加data
中的元素,而不是整个数组。为此,请使用concat
方法。
this.nArray.push(this.nArray.concat(data));
或者使用扩展运算符...
的简短语法:
this.nArray.push(...data);
注意:
我建议您使用const
作为数组定义,并删除[]
中nArray
的空白分配。此外,不要使用concat
方法来使用散布运算符。
答案 1 :(得分:1)
要合并两个数组时,请使用concat。
const nArray = [];
const arr = nArray.concat(this.data);
您现在可以根据需要使用新的合并数组
答案 2 :(得分:0)
实际上,您正在将一个数组推入一个空数组。因此,这里没有像 overriding 这样的东西。但是,假设this.nArray
已经被一些元素填充,则应该使用spread syntax来连接两个数组,例如:
this.nArray.push(...this.data);
答案 3 :(得分:0)
你知道吗?您可能每次都在重新初始化您的阵列。
尝试这样的事情:
// 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);
};
答案 4 :(得分:0)
另一种向数组添加/插入元素的方法是使用 .splice() 方法。
使用 .splice() 您可以在任何给定的索引处插入一个新元素,要么覆盖当前在该索引号中的内容,要么在不覆盖的情况下插入。
示例:
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' ]
阅读:'编程不是关于你第一次很容易得到什么,而是关于你能弄清楚什么。 -2015,Chris Pine,学习编程
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)
阅读:'编程不在于你知道什么,而在于你能想出什么。 -2015,Chris Pine,学习编程
在此示例中,在索引(位置)6(从 0 开始)处,我们将索引 6 中的 5 个元素替换为第三个参数 - 'know,'。
如果您想插入一个元素而不替换另一个元素,请使用相同的 .splice() 方法,但对于第二个参数,请键入 0。
示例:
let favDrink = ['I', 'like', 'milkshake.']
favDrink.splice(2, 0, 'banana'); //at index position 2, insert 'banana'.
//***Does not replace 'milkshake'***
console.log(favDrink.join(' ');
阅读:'我喜欢香蕉奶昔。'
来源: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice