Javascript - 从数组中弹出一个值,但不在数组的末尾

时间:2022-02-22 01:02:24

I have for example this array (each number is singolar, no one duplicate) called pvalue : 1 2 3 15 20 12 14 18 7 8 (sizeof 10).

我有例如这个数组(每个数字是单数,没有一个重复)称为pvalue:1 2 3 15 20 12 14 18 7 8(sizeof 10)。

I need for example to pop the value "15", and after this pvalue should be 1 2 3 20 12 14 18 7 8 (sizeof 9). How can do it?

例如,我需要弹出值“15”,此后pvalue应为1 2 3 20 12 14 18 7 8(sizeof 9)。怎么办呢?

the pop() function take the value at the end of the array. I don't want this :) cheers

pop()函数获取数组末尾的值。我不希望这个:)干杯

EDIT

编辑

for(i=0; i<pvalue.length; i++) {
    if(pvalue[i]==param) {
        ind=i;
        break;
    }
}
pvalue.splice(ind, 1);

2 个解决方案

#1


6  

You're looking for splice. Example: http://jsbin.com/oteme3:

你正在寻找拼接。示例:http://jsbin.com/oteme3:

var a, b;

a = [1, 2, 3, 15, 20, 12, 14, 18, 7, 8];
display("a.length before = " + a.length);
b = a.splice(3, 1);
display("a.length after = " + a.length);
display("b[0] = " + b[0]);

...displays "a.length before = 10", then "a.length after = 9", then "b[0] = 15"

...显示“a.length before = 10”,然后“a.length after = 9”,然后“b [0] = 15”

Note that splice returns an array of the removed values rather than just one, but that's easily handled. It's also convenient for inserting values into an array.

请注意,splice返回已删除值的数组,而不仅仅是一个,但这很容易处理。将值插入数组也很方便。

#2


9  

To pop the first one off, use:

要关闭第一个,请使用:

first = array.shift();

To pop any other one off, use:

要弹出任何其他一个,请使用:

removed = array.splice(INDEX, 1)[0];

#1


6  

You're looking for splice. Example: http://jsbin.com/oteme3:

你正在寻找拼接。示例:http://jsbin.com/oteme3:

var a, b;

a = [1, 2, 3, 15, 20, 12, 14, 18, 7, 8];
display("a.length before = " + a.length);
b = a.splice(3, 1);
display("a.length after = " + a.length);
display("b[0] = " + b[0]);

...displays "a.length before = 10", then "a.length after = 9", then "b[0] = 15"

...显示“a.length before = 10”,然后“a.length after = 9”,然后“b [0] = 15”

Note that splice returns an array of the removed values rather than just one, but that's easily handled. It's also convenient for inserting values into an array.

请注意,splice返回已删除值的数组,而不仅仅是一个,但这很容易处理。将值插入数组也很方便。

#2


9  

To pop the first one off, use:

要关闭第一个,请使用:

first = array.shift();

To pop any other one off, use:

要弹出任何其他一个,请使用:

removed = array.splice(INDEX, 1)[0];