![](/img/trans.png)
[英]Add an array object in an array or add new index in an array in javascript
[英]JavaScript - add a object to an array when index is unknown?
我有一個數組
var price = ['100','200','300','500'];
如果某個條件適用,我想嘗試輸入一個價格,
var index = prices.indexOf(400);
if(index){
prices.splice(1, 0, '150');
};
var index2 = prices.indexOf(200);
if(index2){
prices.splice(3, 0, '600');
};
現在我的問題是我需要在'300'
之后插入'600'
'300'
。 但是,如果發生第一種情況,則我需要插入值'600'
的索引將發生變化。 在這種情況下,如何在'300'
之后加上'600'
'300'
?
更新
如果出現第一個條件,則數組必須是
// ['100','150','200','300','600','500']
如果不 ,
// ['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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.