最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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

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?

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

EDIT

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

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

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?

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

EDIT

for(i=0; i<pvalue.length; i++) {
    if(pvalue[i]==param) {
        ind=i;
        break;
    }
}
pvalue.splice(ind, 1);
Share Improve this question edited Aug 24, 2019 at 13:05 Zoe - Save the data dump 28.2k22 gold badges128 silver badges159 bronze badges asked Sep 19, 2010 at 12:59 markzzzmarkzzz 47.9k126 gold badges316 silver badges534 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 11

To pop the first one off, use:

first = array.shift();

To pop any other one off, use:

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

You're looking for splice. Example: 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"

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.

发布评论

评论列表(0)

  1. 暂无评论