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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3745768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 02:07:14  来源:igfitidea点击:

Javascript - Pop a value from array, but not at the end of array

javascriptarrays

提问by markzzz

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);

采纳答案by T.J. Crowder

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

您正在寻找splice. 示例: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 splicereturns an arrayof the removed values rather than just one, but that's easily handled. It's also convenient for inserting values intoan array.

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

回答by Delan Azabani

To pop the first one off, use:

要弹出第一个,请使用:

first = array.shift();

To pop any other one off, use:

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

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