当前位置: 代码迷 >> 综合 >> js存储多个键值对儿
  详细解决方案

js存储多个键值对儿

热度:67   发布时间:2023-10-18 21:46:30.0

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) {})
})

使用这种的优点是使用空间小,有多少数据能充多少数据。缺点是不能一一对应

  相关解决方案