简体   繁体   English

用javascript中的相同索引替换Array元素

[英]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. 现在,当我将元素3myArray[0]将替换为3myArray[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();

DEMO 演示

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: 但是,考虑到需要从添加的数组中删除相同数量的元素,您可能需要的是使用concatslice的函数:

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]

DEMO 演示

I think you need something in the lines of: 我认为您需要以下方面的东西:

myArray.unshift(element);
myArray.pop();

Explanation: 说明:

  • unshift: inserts the element on position 0 and moves all other elements one position to the right unshift:将元素插入位置0,并将所有其他元素向右移动一个位置
  • pop: removes last element from array pop:从数组中删除最后一个元素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM