trying to write a javascript quiz for my coding bootcamp. having some issues with retrieving and saving previous high scores from local storage. can someone please explain to me why the below code writes the newScore TWICE to the highScores arrayItems array into local storage? obviously i would not like duplicates. everything else works great except for this! please help me. thank you so much!
// load any existing high scores from local storage as array
let scoresArray = localStorage.getItem('highScores') ? JSON.parse(localStorage.getItem('highScores')) : [];
// save the score and intials to local storage in array
let newScore = [document.querySelector("#initialsInput").value, '' + countdownTimer + ''];
scoresArray.push(newScore);
localStorage.clear("highScores");
localStorage.setItem('highScores', JSON.stringify(scoresArray));
// run the high scores function which will show all high scores, storted and give the user a chance to play again
showHighScores();
thanks for your quick replies. im sorry i was able to supply you with all of the info you needed, but i thought i gave you enough to work with.
i was just writing to let you know i did figure out a work around. while i'm still getting the duplicate entries into the array, before writing it to localstorage i am using a very simple jquery method to remove any duplicates from my array. here's what i ended up doing:
var uniqueNames = [];
$.each(scoresArray, function (i, el) {
if ($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
})
The clear() method of the Storage interface clears all keys stored in
a given Storage object.
https://developer.mozilla.org/en-US/docs/Web/API/Storage/clear
I guess you don't need to clear the localStorage.
I believe you need to add the scenario of how triggering this implementation of adding array to the local storage, as I think you might add it twice instead (I mean if the code you showed us is inside a function or how it's executed exactly)
but from the code above, everything seems to be working fine, I'd like to have more code from your side please to better understand what's going on. also you can remove localStorage.clear as localStorage.setItem will override any existing key with new value
lame work around using jquery to remove duplicates from the array:
var uniqueNames = [];
$.each(scoresArray, function (i, el) {
if ($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
})
Related
I have a code where i am able to add, display and delete objects in local storage and its working but whenever i try to update a particular object, it instead overrides everything instead of just changing the particular one i want
MY CODE
$(".qty-val-ls").on("change", function() {
let record = localStorage.getItem("guestCart");
let index = $(this).attr("id");
if(record == null)
{
recordObj = [];
}else{
recordObj = JSON.parse(record);
}
recordObj[index].price = $(this).val() * parseInt(recordObj[index].price);
localStorage.setItem('guestCart', recordObj[index].price);
})
MY INPUT
<input type="number" class="qty-val-ls" min="1" id="${index}" value="4000" onChange="">
The ${index} here is the id that is in the localstorage and the index in the jquery is the number where the object is like at in the localstorage, it starts from 0, 1, 2 etc
MY ARRAY(OBJECT IN LOCALSTORAGE)
[{"id":"11","name":"Rts 512GB USB Flash Drive Pendrive Memory USB 3.0","price":"3000","img":"newusb.png","qty":1},
{"id":"10","name":"MP3 Music Player Audio Player -Black","price":"5000","img":"mp3.png","qty":1},
{"id":"5","name":"Blue Louis Vuitton Women Bag","price":"10000","img":"newbag.png","qty":1},
{"id":"1","name":"Samsung Galaxy S9 6gb ram, 32gb rom, 16mpbs","price":"100000","img":"newphone.png","qty":1}]
So please how do i change the value after calculating and be able to put it back to where its supposed to be
EDIT: I have checked other similar questions on stackoverflow but none seems to work
I'll try to explain what was also said in the comments and give a good approach. First of all, you were overriding the stored object in localStorage with recordObj[index].price instead of the full recordObj. But, as you stated, storing recordObj and then getting its value gives "[object Object]" because it is parsed to string. Taking into account what I said about being careful when accessing to an items property because it could not exist yet, this code should work for you:
$('.qty-val-ls').on('change', function onChange() {
const record = localStorage.getItem('guestCart');
const recordObj = record ? JSON.parse(record) : [];
const index = $(this).attr('id');
if (recordObj[index]) {
recordObj[index].price = $(this).val() * parseInt(recordObj[index].price, 10);
}
localStorage.setItem('guestCart', JSON.stringify(recordObj));
});
Explaining what I did in more detail:
Get the localStorage item.
Parse it with JSON.parse if exists because it is stringified; if it doesn't exist, initialize it as an empty array.
If exists an item at the given index, set the price as you wanted. I also added the radix parameter to parseInt as it is a good practice and I'm used to follow that ESLint rule (https://eslint.org/docs/rules/radix)
Finally, store the modified (or not) and stringified array.
This is definitely a pretty basic question, but I can't seem to find a solution by myself, nor the answer in the depths of the internet.
Java script skill: Newbie
I am getting Google Forms Item Id's so that I could then edit/delete etc. even after somebody edits outside of my script.
To get them Ids I am using a 'for loop', which comfortably gets them for me in a string. Unfortunately I don't know how to save that result in a variable - always getting a syntax error.
I am also not happy with saving the logger.log in my google sheet.
Any ideas?
This is my code:
function GetItems3(){
var formId = "your-id";
var Form = FormApp.openById(formId);
var ajtems = Form.getItems();
for(var i=0;i<items.length;i++)
{ajtems[i].getId().toString()
Logger.log(ajtems[i].getId().toString())
};
//That saves the logger log in my sheet (DMsheet is a global var)
var A = DMsheet.getRange(15, 6, ajtems.length, 1).setValue(A);}
Thanks in advanc3
There are several things wrong from your code.
1) There is no need to use the .toString() method because getId() already returns the id as a String.
2) You didn't define your ajtems var.
3) You can't declare a var like A and use it at the same line you are declaring it because it hasn't been set yet.
4) You didn't declare DMsheet, this variable should contain your sheet and you would get it using the Class Sheet.
5) You said in your post "Java skill: Newbie". Java and JavaScript are not the same.
This code will help you to solve your issue:
function GetItems3(){
var formId = "your-id";
var Form = FormApp.openById(formId);
var items = Form.getItems();
// Get a sheet from the Spreadsheet you are running your script
var dmSheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
// Create an empty array to save the Form's items
var myArray = [];
for(var i=0;i<items.length;i++){
Logger.log(items[i].getId());
// Sotre the title items in the array
myArray.push(items[i].getTitle());
};
// Set the values in your sheet
dmSheet.getRange(1, 1, 1, items.length).setValues([myArray]);
}
I really recommend you to take your time to read the Apps Script docs. It will help you a lot to improve your coding and clear your doubts on how to use Apps Script in the best way possible.
I have been experimenting with JavaScript, and seem to be dealing what I think is a really dumb lost-in-syntax problem. I have created a simple code that compares data from a Json files with the ones stored in the local storage for matching values:
What I have been unable to do, is getting the code more "elegant" and instead of those ugly (preset) || operands insert another FOR-loop that loops through the local storage data.
What I have been trying is:
var aerei = vristoranti[idris].menu.length;
for (i=0; i<aerei; i++){
var aeromobile = vplanes[counter].book[i].name;
for (j=1; j<4; j++){
if (aeromobile == vplanes[0].d+i){
cont1 ++;
}
}
cont2+=cont1;
}
I tried / "d"+i / 'd'+i / 'd+1' / store the int for the converting it into string and concat...etc, etc, but nothing seems to be working. Doing vplanes[0].randomvariable doesn't work either, cause the parser tries to find the var "randomvariable" in the local storage, instead of the value of that variable (looped as d1, d2, d3).
Can someone tell me what am I missing?? I thank you all in advance and wish you a great we.
You can use:
vplanes[0]['d' + i]
I am trying to find occurrences of a string in another string that has been pulled from the HTML document. The page is an SNMP monitor but we have been having issues in the past with CTRL + F because it only wants to find the string within the current viewport of the browser. My attempt at getting around this and not having to look through things manually was to write a script.
The issue here is that it appears the docHTML variable is only able to hold so much data and anything else is truncated. I have looked around on Stack Overflow and found that my string size is significantly less than other people have tried, so that shouldn't be the issue.
All of the IP addresses in the 'ipArray' variable do exist on the page in different locations and are in the docHTML variable when I look through it myself. When I run the doSearch function at various points in the page (viewport dependent) it gives me different results.
I really don't know what has gone wrong here as the code does work sometimes, and not other times. My goal is to have the code go through the whole page and find all missing IP's and add them to the array so that we can go ahead and add them instead of having to compare 490 IP's on a spreadsheet to up to 490 in the monitoring utility.
Thanks in advance!
var docHTML = document.documentElement.outerHTML;
var missing = [];
function doSearch(text) {
if (docHTML.search(text) == -1){
missing.push(text);
}
}
var ipArray = [
"192.168.64.236",
"192.168.64.237",
"192.168.64.238",
"192.168.64.10",
"192.168.64.11",
"192.168.64.12",
"192.168.65.40",
"192.168.65.47"
];
var Total = ipArray.length;
for(i=0;i<Total;i++){
doSearch(ipArray[i]);
}
console.log("Missing IP's: " + (Total - missing.length));
console.log(missing);
Here is the solution, not much of change, just a tweak to your logging statement. You were printing "total-missing" which is wrong. What we need is the missing count-
var docHTML = document.documentElement.outerHTML;
var missing = [];
function doSearch(text) {
if (docHTML.search(text) == -1){
missing.push(text);
}
}
var ipArray = [
"69.171.224.11",
"199.59.149.230",
"174.121.194.34",
"209.200.154.225",
"69.174.244.50",
"67.201.54.151"
];
var Total = ipArray.length;
console.log(Total);
for(i=0;i<Total;i++){
doSearch(ipArray[i]);
}
console.log("Missing IP's: " + (missing.length)); /***HERE***/
console.log(missing);
Other than this, the whole code worked for me as expected. Let me know what else/exactly is the issue. Happy to help.
The code works as intended. The issue happened to be the SNMP monitor it is running on top of. Everything on the page seems to be loaded by POST requests as you scroll. It seems to grab a few before and after which was why I was able to see it in the code and not when executing.
ok. I have a dropdown. well call it dropdownA. I have several arrays already fashioned, that i want to loop through, and put each individual value out onto the page into it's own input field, based on the selection in the dropdown. I know how to put together the loop to get the values out onto the page. anyway, here is the meta code.
meta1array=new Array('','','','','','');
meta2array=new Array('','','','','','');
meta3array=new Array('','','','','','');
function metacode(id){
{
var a=get.the.dd.selIndex;
var b=get.the.dd.options[a].value; //comes back as 'meta1'. other opts are meta2, meta3
var c=b+'array';
for(i=0;i<c.count;i++)
{
loop here to popout values
}
}
i have looked everywhere, and i haven't come up with anything. I also admit that my brain is starting to mushify from a few weeks straight of coding, and this is the first time i have come across this. so, please. i would be greatful for any help.
Global variables are members of the window object.
var c = window[b + 'array'];
It might be wise to make your arrays members of some other object though, for tighter scoping (avoid cluttering the global namespace).
metaobject = {
meta1array: ['','','','',''],
meta2array: ['','','','',''],
meta3array: ['','','','','']
};
// snip
var arr = metaobject[b + 'array'];
for(var i=0;i<arr.length;i++) {
//do work
}
Check out the fiddle using jquery here.