How to give javascript sessionStorage new name with loop - javascript

I am trying to make a button, which creates some data and saves it in the sessionStorage. I want to give every data a key number from 0 and up. The first time the button is pressed it gets the name/key 0. If the button is then pressed again the name for the new data string/object would be 1 and so on. The thing is that I dont want to overwrite existing data in sessionStorage, so it should check if there is a string/object in the sessionStorage; if yes give it a new name, if no save it.
In my following code, cpData is the data I want to store in sessionStorage:
for (var index = 0; index <= window.sessionStorage.key(index); index++) {
if (index > window.sessionStorage.key(index)) {
window.sessionStorage.setItem(index, cpData);
break;
}
};

I found out by myself. This code should do it if one is needs the to do the same:
for (var index = 0; index >= window.sessionStorage.key(index); index++) {
if (window.sessionStorage.key(index) === null) {
window.sessionStorage.setItem(index, JSON.stringify(cpData));
break;
} else if (index > window.sessionStorage.key(index)) {
window.sessionStorage.setItem(index, JSON.stringify(cpData));
break;
}
};
This time it checks wether or not window.sessionStorage.key(index) isn't there. If so it will create a datastring. The break; statement stops the loop immediately. Now the next time the button is pressed and the loop is started, it can see that there is already a datastring, it will then continue to loop until index value is bigger than the key biggest key value at the moment. When it is bigger than al previous saved data, it will save the data and break; the loop.
If one wants to check it by him/herself add this to the same script:
var i = 0, oJson = {}, sKey;
for (i; sKey = window.sessionStorage.key(i); i++) {
oJson[sKey] = window.sessionStorage.getItem(sKey);
}
console.log(oJson);
This will print out ALL sessionStorage data in console.

Related

How to grab an objects property that is stored in an array on a click event

I have this Object and I spawn it onto the canvas after one is picked and pushed into my array.
function grabObjProp(){
var randomInt = Math.floor(Math.random() * 10) + 1;
goodProp = {};
goodProp["name"] = "goodguy";
goodProp["MC"] = new lib.goodObj();
badProp = {};
badProp["name"] = "badguy";
badProp["MC"] = new lib.badObj();
if(randomInt < 7)
ObjArray.push(goodProp);
else
ObjArray.push(badProp);
createObj();
}
I then run an if/else to see if I am clicking the good or the bad and based off that I then either run a gameOver function or I continue the game. My current issue is that my if/else checks the last array that was added and if I badguy is added when I click a goodguy the condition is met and the game ends. I wanted to know how to get the name of the object I clicked store it to a variable then compare that variable when I click and object.
function Click(e){
if(ObjArray[ObjArray.length - 1].name != "goodguy"){
addGameOverScreen();
}else{
numClicked +=1;
scoreTxt.text = numClicked;
exportRoot.removeChild(e.currentTarget);
grabObjProp();
//}
}
Edit** added -1 to if(ObjArray[ObjArray.length].name != "goodguy")so that the if was always check the last index of the array.

Two conditions in for loop

I have this code which im echoing data from jquery success .
for(i = 0;i < dat.id.length; i++){
// im echoing data here
}
and i want check for the highest value in dat.voteup
like that (It works)
var maxvoteup = 0;
if (dat.voteup[i] - dat.votedown[i] ==maxvoteup) {
console.log(maxvoteup);
//i want fetch maxvoteup here
}
But i want make just one For loop not two . How can i do that pls?
EDIT:
var maxvoteup = 0;
for (i = 0;i < (dat.voteup-dat.votedown).length ;i++) {
if (dat.voteup[i] - dat.votedown[i]>maxvoteup) {
maxvoteup = dat.voteup[i] - dat.votedown[i];
console.log(maxvoteup);
//i want fetch maxvoteup here
}
}
EDIT2:
this is what im getting in my jquery response , But actually my max vote is 10 not 8 . 8 is just voted up to 8 , but there is other votes which is 10.
{"status":"success","message":[],"date_edited":[2016-04-21 21:31:25],"voteup":[],"votedown":[8],"id":[]}
Your code is a little hard to read, but if I understand correctly I believe all you need to do is combine both into a single loop with maxvoteup defined outside.
var maxvoteup = 0;
for(i = 0;i < dat.id.length; i++){
// echo data...
// max upvote
if (dat.voteup[i] - dat.votedown[i] == maxvoteup) {
console.log(maxvoteup);
}
}
EDIT:
Unfortunately getting the maximum value from a list requires you to iterate through the list, i.e., a maximum value cannot be found in constant time. I suggest you first find the maximum, and then proceed with your for loop.
Also, if you know your maximum is a list of numbers, you can actually use Javascript's apply to make the code a little cleaner:
var maxvoteup = Math.max.apply(Math, listOfMaxVotes);
See here: How does the Math.max.apply() work?
EDIT2:
If you want to continuously keep track of the maximum, then all you need to do is move the maxvoteup variable to outside of your response handlers so you can always keep track.
// global scope...
var maxvoteup = 0;
// your jquery response handler
var onSuccessData = function(data) {
// get the highest possible max from the `voteup` and `votedown` lists
var responseMax = Math.max.apply(Math, data.voteup.concat(data.votedown));
// check if it's greater than our global maxvoteup
if (responseMax > maxvoteup) {
// if it is, then update our global `maxvoteup` to the new value
maxvoteup = responseMax;
}
// continue with your other processing...
};

Nested 'for' loop - array undefined

I am working on a JS where I want to create a simple game that starts by chosing number of players, name of each player and whether a player is a dealer or not. There can be only one dealer for each game:
function player(playerName, playerDealer) {
this.playerName = playerName;
this.playerDealer = playerDealer;
}
var playerNumber = prompt('Nr of players?');
var playersArray = [];
for (i = 0; i < playerNumber; i++) {
var j = i + 1;
var dealerAssigned = false; // control variable to check whether dealer has been assigned
var inputName = prompt('Name of player nr ' + j);
var inputDealer = prompt('Is player ' + inputName + ' also a dealer? (yes/no)');
playersArray[i] = new player(inputName, inputDealer);
for (k=0;k<playerNumber;k++){ // I want to go through the players array to check if dealer has been assigned
if (playersArray[k].playerDealer == 'yes') {
dealerAssigned=true;
break;
};
};
if(dealerAssigned){ //if dealer has been assigned, don't add the current player to the array and continue with the next iteration
alert("already assigned");
continue;
};
};
I need to include a simple test into the loop that would check if the dealer has been appointed. If so, I want the script only to alert 'already assigned' and skip to the next player. But I am constantly getting the following error
TypeError: playersArray[k] is undefined
Can anybody explain why is it undefined?/What am I doing wrong?
The bug you're specifically asking about appears to me to be that you're iterating over undefined array values, as the error you're getting suggests.
You're getting the number of players you want in line
var playerNumber = prompt('Nr of players?');
Then, you proceed to have two iterations (one nested in the other), in which the inner loop is trying to access values that haven't yet been assigned since the outer loop hasn't gotten there yet:
for (i = 0; i < playerNumber; i++) {
playersArray[i] = new player(inputName, inputDealer);
for (k=0; k < playerNumber; k++) {
if (playersArray[k].playerDealer == 'yes') {
...
}
}
}
It appears to me that the logical error here is the nested loop. I recommend just initializing all players in one loop, then verify that all players have an assigned dealer afterward.
I should add that I'm being intentionally myopic here and focusing very narrowly on the question asked and overlooking other issues I see.
Your for loop inside a for loop is iterating over an array that hasn't been filled yet.
First iteration playersArray[j] = new Player(...) makes the array [Player] or an array of one element! Yet the second loop is looking for an array of many elements. once you look for playersArray[1] but there is only playerArray[0] you get undefined and so undefined.playerDealer causes a TypeError.
`This is your structure stipped-down:
for (i = 0; i < playerNumber; i++) {
playersArray[i] = new player(inputName, inputDealer);
for (k=0;k<playerNumber;k++)...{
//anything with index k > i is undefined, since your outer loop
//hasn't initialized it yet.
}
}
It seems that your i-loop is trying to insert elements for the size of the array to be, but your k-loop is trying to also access the entire array instead of just the initialized portions. Limit this to for (k=0; k<i+1 ;k++) so you only check the previously initialized values of you playersArray

deleting an item from array and add it to another array

I'm trying to delete an item from an array and add it to another array. The array states consists of a list of 50 states. User needs to enter the name of a state and the state must get deleted from states array and get added to the array correctState. Here is my code
function searchString()
{
var total = 50;
var string = document.getElementById("txtState").value;
var element = document.getElementById("status");
for (i=0; i < states.length; i++)
{
if(states[i].toUpperCase() == string.toUpperCase())
{
count = count + 1;
//element.innerHTML = "CORRECT!!!"
addElem = states.splice(i,1);
correctState.push(addElem);
/*for (j=0; j < correctState.length; j++)
{
if(correctState[j].toUpperCase() == string.toUpperCase())
{
element.innerHTML = "Already Submitted. Try another State";
}
}*/
}
document.getElementById("score").innerHTML = count +"/"+ total;
document.write(states);
document.write(correctState);
}
}
Enter State : <input type="text" name="txtState" id="txtState"><span id="timer"></span><br /><span id="status"></span>
<button type="button" name="btnPlay" id="btnPlay" accesskey="s" onClick="searchString()"><u>S</u>ubmit</button>
I'm not able to achieve what I need. I'm new to javascript and need help.
Re these lines:
addElem = states.splice(i,1);
correctState.push(addElem);
splice doesn't return the element that you remove, it returns an array of those elements. So your code is pushing array instances onto correctState. I'd do this:
correctState.push(states[i]); // First push the matching state onto `correctStates`
states.splice(i,1); // ...then remove it
Alternately, you could do it in the order you showed, you just have to get the removed element out of the array you get back
addElem = states.splice(i,1);
correctState.push(addElem[0]);
// Here -----------------^^^
but again, I'd do it by pushing first, then removing.
Separately, I'd use the debugger built into your browser to single-step through that code and watch it run. I suspect you'll find that you want to move some things around, and you almost certainly want to stop looping once you've found that string matches something in the array.
My guess is that it's the fact that you're modifying your states array while you are still enumerating.
So say you're states array is [AR, LA, CT] and the user entered LA. So your for loop goes like this
i = 0 (length is 3 so i < 3)
string not found
i = 1 (length is 3 so i < 3)
string found, remove it from states
i = 2 (length is 2 so i < 2 fails and there's no final loop)
What you probably want is just something like this
function moveAllInstancesBetweenArrays(val, source, destination) {
var indexOfVal = source.map(function(s) { return s.toUpperCase() })
.indexOf(val.toUpperCase());
if(indexOfVal == -1)
return;
source.splice(indexOfVal, 1);
destination.push(val);
moveAllInstancesBetweenArrays(val, source, destination); //continue until all matching are moved
}
moveAllInstancesBetweenArrays(yourSearchVal, states, correctStates);

How to compare Array value to result of 'for' loop in javascript

I have an empty array (called zoomthumbsarray) which gets values pushed to it whilst a 'for' loop is running. This 'for' loop is checking if a thumbnail image is present in the backend against the particular product the user is viewing. If there is an image it gets added into a vertical slider. The current issue is there are non colour specific images (like lifestyle shots) that are being added into the slider multiple times.
So I need to check if the image found in the for loop is currently stored in the array. If it is present, the image has already been generated and I don't want it to get pulled into the slider again. If it hasn't then the image will get added.
Below is the code I am working on. I would presume indexOf would be used but can't get this to work.
Any help would be really appreciated.
var zoomthumbsarray = [] // Empty array which gets populated by .push below during loop
for (var i = 0; i < storeImgsArr.length; i++) { // storeImgsArr finds the quantity of attributes present against the product. This loops and increments counter if there is another attibute image
for (var e = 0; e < storeImgsArr[i].images.imgL.length; e++) { // Loop and increment counter if there is a Large image
zoomthumbsarray.push(storeImgsArr[i].images.imgS[e].slice(-16)); // Slices off last 16 characters of image path i.e. _navy_xsmall.jpg or 46983_xsalt1.jpg and pushes this into 'zoomthumbsarray' array
// if statement sits here to build the html to add the image to the slider
}
}
zoomthumbsarray = [] // Resets array to zero
ANSWER
As answered by Chris I used $.unique to only keep unique values in the array.
Then wrap an if statement around the code to build the thumb image html if the array === 0 or if the current image isn't already in the array.
Updated code below:
var zoomthumbsarray = [] // Empty array which gets populated by .push below during loop
for (var i = 0; i < storeImgsArr.length; i++) { // storeImgsArr finds the quantity of attributes present against the product. This loops and increments counter if there is another attibute image
if (zoomthumbsarray === 0 || zoomthumbsarray.indexOf(storeImgsArr[i].images.imgS[e].slice(-16)) < 0) { // If statement is true if array === 0 or if the current image isn't already in the array
for (var e = 0; e < storeImgsArr[i].images.imgL.length; e++) { // Loop and increment counter if there is a Large image
zoomthumbsarray.push(storeImgsArr[i].images.imgS[e].slice(-16)); // Slices off last 16 characters of image path i.e. _navy_xsmall.jpg or 46983_xsalt1.jpg and pushes this into 'zoomthumbsarray' array
zoomthumbsarray = $.unique(zoomthumbsarray); //Keeps only unique elements
// if statement sits here to build the html to add the image to the slider
}
}
}
zoomthumbsarray = [] // Resets array to zero
Some cheap and dirty ideas:
Using underscore/lodash:
zoomthumbsarray = _.uniq(zoomthumbsarray); //Keeps only unique elements
jQuery has one as well:
zoomthumbsarray = $.unique(zoomthumbsarray); //Keeps only unique elements
then you loop through the array and build HTML.
Update:
There's something a bit odd about the rest of the JS. Might this work (if you're using a new enough browser)?
var zoomthumbsarray = [];
storeImgsArr
.map(function(item) { return item.images.imgS; })
.forEach(function(imgS) {
zoomthumbsarray = zoomthumbsarray.concat(imgS.map(function(imagePath) {
return imagePath.slice(-16);
}));
});
zoomthumbsarray = $.unique(zoomthumbsarray);
I have tried indexOf (see first if statement below) but this doesn't work.
As #elclanrs said, indexOf does return the index in the array not a boolean. You only will need to see if it's >= 0 to test whether an image is already contained in the array.
var zoomthumbsarray = [];
for (var i = 0; i < storeImgsArr.length; i++) {
for (var e = 0; e < storeImgsArr[i].images.imgL.length; e++) {
var image = storeImgsArr[i].images.imgS[e].slice(-16);
if (zoomthumbsarray.indexOf(image) < 0) { // not yet in the array
zoomthumbsarray.push();
// and build the html to add the image to the slider
}
}
}
If you have really lots of images and notice this starts slowing the page down, then there are too many images in your page anyway. No, joke aside; …then check the optimisation by #Ivey.
instead of using an array you can use an object to store the images as keys and a dummy value (possibly true). then you can extract the keys from this object.
var images = {};
for (var i = 0; i < storeImgsArr.length; i++) {
for (var e = 0; e < storeImgsArr[i].images.imgL.length; e++) {
images[storeImgsArr[i].images.imgS[e].slice(-16))] = true;
}
}
var zoomthumbsarray = [];
for(var k in images) {
zoomthumbsarray.push(k);
// build the html to add the image to the slider
}
EDIT: Added build html comment

Categories

Resources