我有這個 javascript/jQuery 代碼:
var json = [
{
id: 0,
text: 'enhancement'
},
{
id: 1,
text: 'bug'
},
{
id: 3,
text: 'invalid'
},
{
id: 4,
text: 'wontfix'
}
];
delete json[2]
console.log(json)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
此代碼洗掉陣列鍵 2。但在那之后我需要重新索引,以便我可以訪問其他 3 個值,例如:
json[0]
json[1]
json[2]
我怎么能意識到這一點?
uj5u.com熱心網友回復:
使用splice而不是delete像下面這樣(W3schools splice):
json.splice(target_index,1);
請閱讀有關拼接方法的Mozila 頁面以獲取更多資訊。
uj5u.com熱心網友回復:
如果你不想改變值,你可以簡單地過濾陣列
json.filter((i, idx) => idx !== 2)
uj5u.com熱心網友回復:
您可以通過簡單地使用重新索引
json.filter(function(){return true;})
這是一個作業演示。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#delete").click(function(){
var json = [
{
id: 0,
text: 'enhancement'
},
{
id: 1,
text: 'bug'
},
{
id: 3,
text: 'invalid'
},
{
id: 4,
text: 'wontfix'
}
];
delete json[2]
console.log(json.filter(function(){return true;}))
});
});
</script>
</head>
<body>
<button id="delete">delete</button>
</body>
</html>
uj5u.com熱心網友回復:
Splice 方法從陣列中洗掉元素,并在必要時在它們的位置插入新元素,回傳洗掉的元素。
splice(start: number, deleteCount?: number)
json.splice(2, 1);
uj5u.com熱心網友回復:
從陣列中洗掉所有空項的快速技巧是:
.filter(Boolean)
這將陣列中的專案傳遞給Boolean()物件,該物件將每個專案強制為真或假,如果為真則保留它。因此,它將從陣列中洗掉每個undefined、false、null、0和空字串 ( '') 值。
更多資訊:過濾器、布林值。
例子
json = json.filter(Boolean)
用你的代碼
var json = [
{id: 0, text: 'enhancement'},
{id: 1, text: 'bug'},
{id: 3, text: 'invalid'},
{id: 4, text: 'wontfix'}
]
delete json[2]
json = json.filter(Boolean)
console.log(json)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/354081.html
標籤:javascript 查询 数组
