简体   繁体   中英

JavaScript - add a object to an array when index is unknown?

I have an array

var prices = ['100','200','300','500'];

i'm trying to insert a price if one condition apply,

var index = prices.indexOf(400);

if(index){  
       prices.splice(1, 0, '150'); 
         };



var index2 = prices.indexOf(200);

    if(index2){  
           prices.splice(3, 0, '600'); 
              };

Now my problem is i need to insert '600' after the '300' . but, if 1st condition happened the index which i need to insert value '600' would be change. in this situtation how can i add '600' after the '300' ?

Update

if 1st condition occurs the array have to be,

// ['100','150','200','300','600','500']

if not ,

// ['100','200','300','600','500']

html =>

<div id="demo"> </div>

javascript =>

var prices = ['100','200','300','500'];
document.getElementById("demo").innerHTML = prices;

function myFunction() {

    var index = prices.indexOf('400');
    if(index >= 0){
        prices.splice(1, 0, '150'); 
    }

    index = prices.indexOf('300');

    if(index >= 0){
        prices.splice(index + 1, 0, '600'); 

    }

    document.getElementById("demo").innerHTML = prices;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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