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

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)

Related

Object property is treated as null after setting with Number() even though it logs as having value

I'm running into a strange issue where I cannot access a field of an object I have defined unless I explicitly set that field to a number value.
I am trying to access the field with the following
if (userCache[mem.id][action.field]) {
this if block is not being entered. I am console.log()'ing the above value before this conditional, and it shows the value as 0, which is what it was previously set to using:
if (!isNaN(action.fieldvalue)) {
valToSet = Number(action.fieldvalue);
} else {
valToSet = action.fieldvalue;
}
userCache[mem.id][action.field] = valToSet;
Where action.fieldvalue is the value I want to set, but it's a string. If I instead set the value using = 0 , instead of = Number(), then I am able to access it correctly in the conditional.
This should help you understand the scenario:
$ node
> const a = '0';
> const b = Number('0');
> if (a) { console.log("true") } else { console.log("false") }
> if (b) { console.log("true") } else { console.log("false") }
To clarify, "0" string is not a falsy value since its not empty but 0 number is.

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

If statement is not working properly

I'm trying to change the condition in which data is written to a table. I noticed a strange result when trying to change this: it seems WriteToTable function would runno matter what if condition I subjected it to. To test this I did the following:
var TestThis=0;
if (TestThis=1000){
WriteToTable(iPlaceDisplayNum, place.name, place.rating, xScoreFinal, iProspect, place.url, place.formatted_phone_number);
alert ('This alert should not be displaying.');
}
The function will still execute and the alert will be still be displayed when the script runs. I'm not sure why?
Here's the rest of the function, the problem is towards the bottom:
function printme(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
if (typeof place.reviews !== 'undefined') {
var xScore = 0;
var xGlobal = 0;
for (var i = 0; i < place.reviews.length; i++) {
reviews = place.reviews[i];
for (var x = 0; x < reviews.aspects.length; x++) {
aspectr = reviews.aspects[x];
xScore += aspectr.rating;
xGlobal++;
}
}
var xScoreFinal = (xScore / xGlobal);
}
if (typeof xScoreFinal !== 'undefined') {
iPlaceDisplayNum++;
var iProspect;
if (xScoreFinal < 2.3) {
iProspect = 'Yes';
}
//Not sure what's going on here
var TestThis=0;
if (TestThis=1000){
WriteToTable(iPlaceDisplayNum, place.name, place.rating, xScoreFinal, iProspect, place.url, place.formatted_phone_number);
alert ('This alert should not be displaying.');
}
}
}
}
You are assigning a value to your variable in your if condition check. Your TestThis variable is being assigned value 1000, which will be true after being converted to boolean by JavaScript. That's why your function is being always executed. You can read more about the automatic type conversion here.
Now to fix your code, change this -
if (TestThis=1000)
to this -
if (TestThis == 1000)
or if you don't want automatic type conversion -
if (TestThis === 1000)
Sometimes people like to reverse the values in the comparison, in the following way -
if (1000 === TestThis)
This is called a Yoda Condition (yeah, named after the Grand Jedi Master Yoda) . The benefit is that in case someone mistakenly puts only a single equal, it will result in an error as you cannot assign anything to a constant. I have never used it personally though (and probably never will because I find it rather unconventional).
JavaScript allows you to assign a value in a conditional, so this TestThis=1000 results to 1000 and in a conditional statement positive numbers (actually anything not 0) result to an evaluation to true.
To make it a conditional, you should do TestThis===1000 (and you should almost always use the === over the == as the === forces an actual comparison of the two and doesn't try to convert one part of the conditional to equal the other.)
You can also do 1000 === TestThis (or conversly 1000 == TestThis) Some people say this is bad coding, because it's difficult to read. I'll leave that up to you to decide, but this absolutely won't allow you to accidentally assign a value in the conditional because you can't assign a value to 1000.
In the if statement, you're setting TestThis to 1000, rather than comparing it to 1000. The = operator returns the value that was set, which evaluates to true because it is not undefined, 0, or null. You simply need to use the == operator.
if(TestThis == 1000)
if (TestThis == 1000)
Change like this.
For comparing equality in if you must have ==
Change:
if (TestThis=1000)
To:
if (TestThis==1000)
You're actually assigning to TestThis which will return true and execute the conditional block.

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
}

Count Up window.localStorage.getItem via 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>

Categories

Resources