[英]Replacing Array element with same index in javascript
I have an Array like 我有一个像
var myArray = new Array;
I have to push some elements to array in such a way that the elements will be replaced with same index
. 我必须将某些元素推入数组,以便将这些元素替换为相同的
index
。
Example :
myArray.push(1);
myArray.push(2);
myArray.push(3);
so now 所以现在
myArray[0] = 1
myArray[1] = 2
now when i will push element 3
then myArray[0]
will be replaced with 3
and myArray[1]
will be replaced with 1
and the element 2
will be removed. 现在,当我将元素
3
推myArray[0]
将替换为3
, myArray[1]
将替换为1
,元素2
将被删除。
It will continue according to the number of elements pushed... 它将根据推送的元素数继续进行...
Can any body help me with this requirement... 任何人都可以帮助我实现这一要求...
push
adds to the end of an array. push
将添加到数组的末尾。 If you want to add a value to the beginning of an array you can use unshift
. 如果要将值添加到数组的开头,则可以使用
unshift
。
myArray.unshift(3);
You can then use pop
to remove the last element: 然后,您可以使用
pop
删除最后一个元素:
arr.pop();
However, what you might need, given that you need to remove the same number of elements from an array that you add is a function that uses concat
and slice
instead: 但是,考虑到需要从添加的数组中删除相同数量的元素,您可能需要的是使用
concat
和slice
的函数:
function pusher(arr, add) {
return add.concat(arr).slice(0, arr.length);
}
var arr = [1, 2, 3, 4];
var arr = pusher(arr, [5, 6]); // [5, 6, 1, 2]
I think you need something in the lines of: 我认为您需要以下方面的东西:
myArray.unshift(element);
myArray.pop();
Explanation: 说明:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.