值被添加到带有键的对象中。
id 的起始值设置为 0。我试图找到一种方法来增加 id 而不将其重置为给定的 0 值。
当值增加时,新值(id)被推入对象,然后这个对象被推入数组(具有所有输入值和id值,然后被推入主localStorage)。然后将新值(增加的 id)保存到 localStorage 中(仅用于 id )。
每次新点击都需要访问 id 的 localStorage 并使用“for 语句”循环它以接收值(每次创建新 id 时,数组的长度。这会导致点击无限循环)出现问题。
需要一种将增加的 id 推入主数组(所有值)的方法,同时可以访问增加的 id 的最后一个值,以便它可以再次增加。
let testObjectOne = {
//'title' is key and $title.val() is value of that key
'title': $title.val(),
'typ': $typ.val(),
'assign': $assign.val(),
'files': $file.val().match(/[\/\\]([\w\d\s\.\-\(\)]+)$/)[0],
'priority': $priority.val(),
'category': $category.val(),
'textField': $textField.val(),
'end_date': $date.val(),
'id':id,
};
let id = 0;
let array_id = [];
array_id.push(id);
let string_array_id = JSON.stringify(array_id);
localStorage.setItem('id' , string_array_id);
let savedId = localStorage.getItem('id'),
array_savedId = JSON.parse(savedId);
console.log(savedId);
console.log(array_savedId);
//looping id array
for (let k = 0; k < array_savedId.length; k++){
console.log(array_savedId[k]);
//increments 0 to 1 , later on increments 0 to 1 and 1 to 2 and so on
let newValue = array_savedId[k] + 1;
//checks if new value is not matching to values in array
if (newValue !== array_savedId[k]){
//then pushes new value into array creating new index
array_savedId.push(newValue);
//id inside testObjectOne is set to new value
testObjectOne['id'] = newValue;
//pushing testObjectOne into main array
let save_newValue_withID = localStorage.getItem('key'),
array_s_nV_wID = JSON.parse(save_newValue_withID);
array_s_nV_wID.push(testObjectOne);
let string_newValue_withID =JSON.stringify(array_s_nV_wID);
localStorage.setItem('key' , string_newValue_withID);
}
}
let test = localStorage.getItem('key'),
array_test = JSON.parse(test);
array_test.push(testObjectOne);
let back_to_string = JSON.stringify(array_test);
localStorage.setItem('key', back_to_string);
let testObjectOne = {
'title': $title.val(),
'typ': $typ.val(),
'assign': $assign.val(),
'files': $file.val().match(/[\/\\]([\w\d\s\.\-\(\)]+)$/)[0],
'priority': $priority.val(),
'category': $category.val(),
'textField': $textField.val(),
'end_date': $date.val(),
'id': 0,
};
if (localStorage.getItem('key') === null) {
localStorage.setItem('id', "0");
let temp_Array = [];
temp_Array.push(testObjectOne);
localStorage.setItem('key', JSON.stringify(temp_Array));
} else {
let id_value = localStorage.getItem('id');
let temp_array = JSON.parse(localStorage.getItem('key'));
id_value++;
testObjectOne['id'] = id_value;
temp_array.push(testObjectOne);
localStorage.setItem('key', JSON.stringify(temp_array));
localStorage.setItem('id', id_value);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句