js存儲多個鍵值對兒
背景
經常在開發過程中碰到這種情況,比如需要保存某個人的分數,那么就需要在頁面上填寫分數,如果是在table中填寫的話,需要多個人的多個分數,如何做到一一對應。目前提供兩個版本。
使用字典類型保存
需要保存用戶的id和用戶的分數,那么可以以id為key,分數為value進行保存。以下為代碼
$('#btn_post_page_verti').on('click', function () {
let dictionary = new Array(10);
$("input[name='inp_items_info_pro']").each(function () {
let id = $(this).val();
let ver_num = $(this).parents('tr').find('td').eq(6).find('#inp_vertifyNumber').val();
dictionary[id] = ver_num;
});
console.log(dictionary)
console.log(dictionary.length)
if (dictionary.length === 0) {
alert("您沒有選中任何數據,請點擊復選框后重試!");
}
})
這種做法的優點是一一對應,方便傳輸。缺點是無法將id映射成為string,這就證明了,如果你的id最大號是1000或者更大的數,js會為你開辟1000或者更大的空間,空間浪費極大,而且聲明了空間大小也沒用。還有有可能會有這種想法,將id變成string,我試過,但是不管用。也是會按照最大的id進行開辟空間。
使用數組保存
$('#btn_post_page_verti').on('click', function () {
let ids = new Array();
let numbers = new Array();
let idsCount = 0;
let numbersCount = 0;
$("input[name='inp_items_info_pro']").each(function () {
ids[idsCount++] = $(this).val();
});
$("input[name='inp_vertify_pro_number']").each(function () {
numbers[numbersCount++] = $(this).val();
});
console.log(ids);
console.log(numbers);
$.post('/manage/postPageVertify',{
ids:ids,
numbers:numbers
},function (response) {
})
})
使用這種的優點是使用空間小,有多少數據能充多少數據。缺點是不能一一對應