Count Up window.localStorage.getItem via Javascript - javascript

I try to could a number in localStorage but the ++ doesnt do it any other way?
window.localStorage.setItem('run','++')
This is the full code
<script type="text/javascript">
if(window.localStorage.getItem('run')==null){
window.localStorage.setItem('run','1')
}
else if(window.localStorage.getItem('run')==1){
window.localStorage.setItem('run','++')
window.location = "index_aerosoft.html";
}
else if(window.localStorage.getItem('run')==25){
alert("hey 25times");
window.localStorage.setItem('run','null')
};
</script>

localStorage only contains strings.
If you want to keep a counter in it, you have to parse it :
var c = parseInt(localStorage['run']||'0', 10); // read, with 0 as default value
c++; // increment
localStorage['run'] = c; // store the incremented value

The local storage only stored strings. And it cannot parse arguments into expressions to increment a value on the fly, you have to do this manually.
So, you first need to grab the value and parse it to an integer:
i = parseInt(window.localStorage.getItem('run'));
Then your can store the incremented value:
window.localStorage.setItem('run',(i + 1));
Note: in your condition
else if(window.localStorage.getItem('run')==1){
you check if a 1 is stored, I suppose you indent to check if the value is smaller than 25? If not, increasing the value is meaningless as the following statement will always be storing 2...

if(window.localStorage.getItem('run')==null){
window.localStorage.setItem('run','1');
alert("First start");
}else if(window.localStorage.getItem('run')==10){
window.localStorage.setItem('run','1');
}else{
var run = window.localStorage.getItem('run');
var irun;
irun = (parseInt(run) + 1);
window.localStorage.setItem('run',irun.toString());
window.location = "index_xyz.html";
alert(window.localStorage.getItem('run'));
}
</script>

Related

how to check if 2 tries at random number are the same?

I am trying to figure out an if statement that will allow me to check whatever the current (Math.floor(Math.random()*5) gave me the same value as the previous attempt? I know I can get It to print it out but is there some way of getting the system to check?
You need to store your previous value and optionally your current value to variables and compare. e.g.:
Given:
function randomInteger(limit) {
return Math.floor(Math.random() * limit);
}
You can store both to variables and compare:
var previousValue = randomInteger(5);
var currentValue = randomInteger(5);
if (currentValue === previousValue) {
/* your conditional code here */
}
Or you can skip storing the current value to a variable and compare the new value directly:
if (randomInteger(5) === previousValue) {
/* your conditional code here */
}
Simply check this boolean:
Math.floor(Math.random()*5) === Math.floor(Math.random()*5)

check if array has the user inputted value

I am using an input field to put user inputs in an array.
I want to check if the user inputted number is already in the array or not. And if it is in the array then the input should not be re-added.
Here is my attempt.
if(e.keyCode === 43){
var num = document.getElementById("numbers").value;
var oks = [];
// set num
// check if num is in the oks array
if( oks[num]==num ){
alert("It is already there.");
}
else{
oks[num.value]=num.value;
}
console.log(oks.value);
}
With the above code it says undefined in the console log.
Please help me find where I am wrong in this.
Thanks a lot :)
Your code has lots of mistakes, such as :
var oks = [];
The above is saying that every time the user inputs something, the array is empty, therefore there is nothing there, therefore the value is not there, so there is no use of trying to know whether the value exists or not, because it doesn't, so you should declare the oks variable outside of the eventListener.
oks[num]
The above is not the value, it's the element in the array whose index is the value, which are very different.
num.value
The above is a syntax error, because the num variable is a number not a dom element that has a value attribute.
And here's the solution to your problem :
if( oks.indexOf(num)>-1 ){
alert("It is already there.");
}
else{
oks.push(num);
}
you can do
if(oks.indexOf(num) != -1)
to check whether it lies in the array or not or alternatively you could use oks as an object and check if a fiels of a similar value is defined or not, which should be more efficient
var oks = [];
is being initialised on every request, hence it is always empty, initialise it at a parent/global scope, you should use
var oks = {};
// at a parent scope
if(e.keyCode === 43){
var num = document.getElementById("numbers").value;
// set num
// check if num is in the oks array
if( oks{num} != undefined ){
alert("It is already there.");
}
else{
oks[num]=true;
}
console.log(oks.num);
}

check if [variable name] + [number] exists?

I'm using the code below to check if var1 exists, then assigning another variable (promt) to store var1 provided that the user types in the variable. Problem is I have about twenty variables I need to check so my code looks like the below times ten:
if (typeof var1 !== 'undefined') {
if(selection==var1){
var promt = var1;
}
}
if (typeof var2 !== 'undefined') {
if(selection==var2){
var promt = var2;
}
}
This (a) makes a ton of inefficient code and (b) may cause errors if I have over twenty variables. Is there a way to check if var1, var2, var3, etc.. exists then stop checking when the variables stop?The goal is to be able to have one hundred variables and still have the same amount of code I would have if there were two.
If your variables are fields on an object you can easily build the field names dynamically:
fieldname = 'var' + index;
if (typeof obj[fieldname] !== 'undefined') {
if (selection == obj[fieldname]){
var promt = obj[fieldname];
}
}
For local variables I however can't provide a solution.
First thing first var is reserved word in javascript, so you cannot use it as variable names, hence I use _var here instead.
I made a jsFiddle for this solution, so check it out pls.
You may also look at the code below:
for (i in _var) {
// Loop through all values in var
if ((typeof _var [i] !== undefined) &&
selection_array.indexOf(_var [i]) >= 0) {
// note that array.indexOf returns -1 if selection_array does not contain var [i]
prompt = _var[i]; // use this if you only want last var[i] satisifying the condition to be stored
prompt_array.push(_var[i]);// use this if you want to store all satisifying values of var[i]
}
}
Also check the below snippet
// Lets declare and give some example value to _var, Note that you cannot use var as variable name as it is a reserver word in javascript
var _var = ['foo1', 'foo2', 'foo3', 'foo4'];
// Declare a variable called prompt (actually not necessary normally)
var prompt;
// Declare a array called prompt_array to store the output
var prompt_array = [];
// Declare and give some example value to selection_array
var selection_array = ['foo2', 'foo3'];
// main program to solve the problem
for (i in _var) {
// Loop through all values in var
if ((typeof _var [i] !== undefined) &&
selection_array.indexOf(_var [i]) >= 0) {
// note that array.indexOf returns -1 if selection_array does not contain var [i]
prompt = _var[i]; // use this if you only want last var[i] satisifying the condition to be stored
prompt_array.push(_var[i]);// use this if you want to store all satisifying values of var[i]
}
}
// output for visualizing the result
document.getElementById('output').innerHTML += 'prompt = ' + prompt + '<br/>';
document.getElementById('output').innerHTML += 'prompt_array = ' + prompt_array.toString();
<div id="output">
</div>
You can ask me through commenting if you have a further problem on this :D.

JavaScript and Array's

EDIT I originally posted this with my version of the J.S but it's so far off no one can even help so i'm starting over. Here is the pseudocode i have done that needs to be translated into a Javascript program. Any help is appreciated!
I am a beginning programmer i understand this code will have multiple errors, that's why i am here. Array's and loops have given me much trouble while trying to learn them and especially with formatting them in JavaScript. The things i know are incorrect or still need i commented out i still need them, i also know i'm not passing anything i just can't seem to wrap my head around how to get them there. I'm also not sure if while gather input i'm using alter and prompt correctly. In the display function the spacing is necessary for when it will be displayed. Corrections and explanations are greatly appreciated.
Module main()
//Declare local variables
Declare endProgram = “no”
While endProgram == “no”
Declare Real notGreenCost[12]
Declare Real goneGreenCost[12]
Declare Real savings[12]
Declare String months[12] = “January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”
//function calls
getNotGreen(notGreenCost, months)
getGoneGreen(goneGreenCost, months)
energySaved(notGreenCost, goneGreenCosts, savings)
displayInfo(notGreenCost, goneGreenCosts, savings, months)
Display “Do you want to end the program? Yes or no”
Input endProgram
End While
End Module
Module getNotGreen(Real notGreenCost[], String months[])
Set counter = 0
While counter < 12
Display “Enter NOT GREEN energy costs for”, months[counter]
Input notGreenCosts[counter]
Set counter = counter + 1
End While
End Module
Module getGoneGreen(Real goneGreenCost[], String months[])
Set counter = 0
While counter < 12
Display “Enter GONE GREEN energy costs for”, months[counter]
Input goneGreenCosts[counter]
Set counter = counter + 1
End While
End Module
Module energySaved(Real notGreenCost[], Real goneGreenCost[], Real savings[])
Set counter = 0
While counter < 12
Set savings[counter] = notGreenCost[counter] – goneGreenCost[counter]
Set counter = counter + 1
End While
End Module
Module displayInfo(Real notGreenCost[], Real goneGreenCost[], Real savings[], String months[])
Set counter = 0
While counter < 12
Display “Information for”, months[counter]
Display “Savings $”, savings[counter]
Display “Not Green Costs $”, notGreenCost[counter]
Display “Gone Green Costs $”, goneGreenCost[counter]
End While
End Module
A few notes:
Currently the program creates a few variables and functions that
don't seem to interact
Most of the edits below are not optimal - there are parts that
could be done by much simpler means (i.e. counter++) - But thats
for you to learn =P
I made quite a few assumptions of what you wanted the program to
do, they might be wrong, they might be right
var notGreenCost = []; //Array lengths don't need to be specified
var goneGreenCost = [];
var savings = [];
var months = ["January", "Feburary", "March", "April", "May", "June"];
//A boolean value (true | false) would suit this better as opposed to "yes"/ "no"
var endProgram = false;
var option = 0;
/* You dont need main functions in javascript
* migrated everything to be global :/
* Delete:
function main(){
// Move this (made it global): var endProgram = "no";
}
*/
// I don't think this is meant to be initMonths..
// Maybe something like getOptions?
function /*initMonths*/getOptions(){
while (endProgram == false){ //lowercase while
//Because prompt would block everything else until it gets input
//we probably want to move the prompt to be after the alerts
alert("options:"); //Clarity
alert("1 to enter data");
alert("2 to display data");
alert("3 to write data to a file");
alert("4 to read data from a file");
//Alter global "option" to take the value of the prompt
option = prompt("What would you like to do? Type:");
//} //I assume you want the rest of the code in this while loop - otherwise it will loop forever
// Delete this bracket (its unmatched): {
// Delete return statement as it will stop the function return option;
// Delete this bracket (its unmatched): }
//Create a variable to take the value of prompt (this should be outside the while loop) but it seem clearer for explanation purposes to be here
var toEnd;
toEnd = prompt("Do you want to end the program (enter yes or no)");
// Javascript uses != for "not equal to" and && for "AND"
while (toEnd != "no" && toEnd != "yes") {
toEnd = prompt("Please enter a value of yes or no");
}
//I think you want to assign the value of toEnd to endProgram
// Note the the below is not the only/best way to do it
if(toEnd == "no") {
endProgram = false;
} else if(toEnd == "yes") {
endProgram = true;
}
// While use brackets not End s
// End While
// End While
}//End while loop here
}
Javascript in a browser cannot alter files - writeToFile, readFromFile have all been removed
I believe you want months to be global, if it is then initMonths is unnecessary
getNotGreen:
function getNotGreen(){
//You don't need to specify types in Javascript
/*Integer*/ var counter = 0
while (counter < 6){ //lowercase while
//I'm assuming you want to combine the values of "Enter NOT GREEN energy costs for" and months[counter] - This is done by using the + sign
//Im also assuming you want to read the value into notGreenCost
//.push adds a value to a array
notGreenCost.push(prompt("Enter NOT GREEN energy costs for" + months[counter]))
//Returning here makes the rest of the function redundant
//}
//return notGreenCost[counter];
//}
//Javascript does not use Set
// Note that below is not the only/best way to do it
/*Set*/ counter = counter + 1
} //End the while loop here
}
getGoneGreen:
function getGoneGreen(){
//Counter should probably be local (not global) - use var
var counter = 0;
while (counter < 6){//lowercase while
//I'm assuming you want to combine the values of "Enter NOT GREEN energy costs for" and months[counter] - This is done by using the + sign
//Im also assuming you want to read the value into notGreenCost
//.push adds a value to a array
goneGreenCost.push(prompt("Enter GONE GREEN energy costs for" + months[counter]));
//See above (getNotGreen)
//}
//return goneGreenCost[counter];
/*Set*/ counter = counter + 1;
}//End while loop here
}
energySaved:
function energySaved(){
//Counter should probably be local (not global) - use var
var counter = 0;
while (counter < 6){//lowercase while
savings[counter] = notGreenCost[counter] - goneGreenCost[counter]
counter = counter + 1;
}
} //I assume you want to end energySaved here?
displayInfo:
function displayInfo(){
//Alert produced individual boxes, i assume you want the following in a single window?
// "\n" is a line break
alert("SAVINGS NOT GREEN GONE GREEN MONTH\n"+
"_________________________________________________\n");
//Counter should probably be local (not global) - use var
var counter = 0;
while (counter < 6){//lowercase while
alert( "$" + savings[counter] + "$" + notGreenCost[counter] + "$" + goneGreenCost[counter] + "" + months[counter]);
counter = counter + 1;
}
} //I assume you want to end displayInfo here?

keep add the value without overwrite the function

function checkData() {
var temp = 0;
var totalMarks = countMark(temp);
if (totalMarks != 100)
window.alert("Marks must total 100");
}
function countMark(mark) {
var totalMark = 0;
totalMark += parseInt(mark)
return totalMark;
}
function doAdd() {
var taskid = document.getElementById("taskid").value;
var taskname = document.getElementById("taskname").value;
var taskmark = document.getElementById("taskmark").value;
if (taskid.length === 0)
window.alert("Task Id cannot be empty!");
if (taskname.length === 0)
window.alert("Task name cannot be empty!");
if (taskmark.length === 0)
window.alert("Task Mark cannot be empty!");
else if (!markpattern.test(taskmark))
window.alert("Invalid data in mark field");
var marks = parseInt(document.getElementById("taskmark"));
if (marks < 0 || marks > 100)
window.alert("Marks out of range. Please re-enter");
countMark(marks);
}
My question is when i keep call the doAdd() function. my marks will keep adding . want to do like passing reference like in C++ . my function countMark(...) will keep adding .
after that, when my form submitted, my form will call the function checkData()
If my totalmark is not 100 . will prompt out the alert and error.
but my code is not working . I guess that my countMark function wrong somewhere
If I understand you correctly, you're looking for the equivalent of a static variable - something that gets initialized the first time the function is called, and keeps it's value for subsequent calls.
Take a look at this related question: https://stackoverflow.com/a/1535650/2444111
The top answer (by CMS) is talking about class-based static variables, which are not quite the same thing.
The second answer (by Pascal MARTIN) is what you're looking for. It takes advantage of the fact that JS functions are also objects, and stores the variable as a property of the function object. This is a better solution than using a global variable (or a property of window, which is what a global actually is)
There are several issues in your code and it's really hard to say what your intention was. But I will address what I found.
In the following piece of code you are requesting a DOM Element and try to parse it as an Integer. The result of that type convertion is always NaN. Maybe wanted to get the value attribute of your element, like you did before. (Also, don't request the same element multiple times. Request it once, save the result in a variable and use that variable from that on).
var marks = parseInt(document.getElementById("taskmark"));
if (marks < 0 || marks > 100)
window.alert("Marks out of range. Please re-enter");
countMark(marks);
Your function countMark is pretty useless, because it will always return whatever Number you pass to it (see comments in your code).
function countMark(mark) {
var totalMark = 0; //create a new variable with value 0
totalMark += parseInt(mark) //add "mark" to that variable
return totalMark; //return that variable => 0 + mark = mark (and if mark = NaN => 0 + mark = NaN)
}
Maybe you wanted to make totalMark a global variable, than you would need to define it outside of your function:
var totalMark = 0;
function countMark(mark) {
totalMark += parseInt(mark);
return totalMark;
}
Last but not least, lets analyse your function checkData:
function checkData() {
var temp = 0; //create a local variable with value 0
var totalMarks = countMark(temp); //pass 0 to countMark => return 0 => totalMarks = 0
if (totalMarks != 100) //always true since totalMarks is always 0
window.alert("Marks must total 100"); //will always alert
}

Categories

Resources