I have a program where I have these strings being added to an array. However, there are many strings that are triggered by a certain condition, which can be met multiple times, however I only want it to be added on the first occurrence. So I have implemented a system where the event of adding the string to the array is triggered by the original condition, and a boolean expression. Here is an example of one of those conditions:
if (count >= 10 && displayMulti == true) {
consoleData.shift()
consoleData.push("Multi available")
displayMulti = false
window.localStorage.setItem("display_multi", String(displayMulti))
updateConsole()
}
When the string is added to the array, the boolean, displayMulti, is set to false so that it will not trigger again. However, upon refreshing the page, it will still trigger. I'm not sure why because I feel like I have saving the values to localstorage correctly. Code is below:
if (window.localStorage.getItem("display_multi") != null ) {
displayMulti = Boolean(window.localStorage.getItem("display_multi"))
} else {
console.log("here")
var displayMulti = true
}
There "here" console log statement is not triggered. So I have no idea why this would keep triggering because I don't see how the boolean is true. I've tested at like so many different points I genuinely have no idea what's wrong. I also don't think those values are affected anywhere else in my code. Any help is appreciated.
Here is a solution that properly parses your string as a boolean. Instead of Boolean(), a conditional (window.localStorage.getItem("display_multi") === 'true')(window.localStorage.getItem("display_multi") === 'true') is used.
if (window.localStorage.getItem("display_multi") != null ) {
displayMulti = (window.localStorage.getItem("display_multi") === 'true')
} else {
console.log("here")
var displayMulti = true
}
if (count >= 10 && displayMulti == true) {
consoleData.shift()
consoleData.push("Multi available")
displayMulti = false
window.localStorage.setItem("display_multi", String(displayMulti))
updateConsole()
}
Related
Do not actually understand why this code part not working as it should.
This useEffect block re-renders on every scrollY position. Also, I see that this code part: console.log(wrapperRef.current.style.opacity); should call if and else if statements, but it does not.
Here is the code:
useEffect(() => {
console.log(wrapperRef.current.style.opacity);
if (wrapperRef.current.style.opacity === 0) {
setIsHidden(true);
console.log("true");
} else if (wrapperRef.current.style.opacity === 1) {
setIsHidden(false);
console.log("false");
}
}, [position]);
As you can see here, style values are strings, but with the === operator you also check for type equality.
This means you check that '0' === 0 which are not the same types and also why your check never enters the if body.
Either check for '0' or use the == operator which does ignore types.
I need to check three conditions,
sheet_exists = 1
recalc = 1
qty_total and new_qty_total are not equal
The if statement works well if only the first 2 arguments are used:
if(sheet_exists === 1 && recalc === 'yes'){
//do something
}
But when I try to add he 3rd argument it fails, the actions in the if statement are ignored. I've tried:
if((sheet_exists === 1) && (recalc === 'yes') && (qty_total !== new_qty_total)){
//do something
}
And:
if(sheet_exists === 1 && recalc === 'yes' && (qty_total !== new_qty_total)){
//do something
}
And:
if(sheet_exists === 1 && recalc === 'yes' && qty_total !== new_qty_total){
//do something
}
Where am I going wrong?
Considering you are happy with the behavior of the first two conditions, and not with the last one, the problem must be in the last one.
Pay attention, qty_total !== new_qty_total will return TRUE only when the value or type of qty_total and new_qty_total are different.
If one is an integer 100 and the other is a string '100' then the condition evaluates as TRUE because they differ on the data type. But if they are both integers it will return FALSE, because neither the value nor the type are different.
To make sure the comparison works ok, make sure both variables are the same data type.
I am trying to compare a database (SQL) value (which is being returned correctly) to the boolean value 'true'. If the database bit value is = true then I want a div element to become visible, else stay hidden.
<script language="javascript">
window.onload= function show_CTL() {
if(<%=_CurrentUser.IsCTL%> == true){
document.getElementById('CTL').style.visibility = "visible";
} else{
document.getElementById('CTL').style.visibility = "hidden";
}
}
</script>
However I am getting the error, Javascript: 'True' is undefined.
I have tried many combinations of <%=_CurrentUser.IsCTL%> == 'true' or "true" or true or "True" or 'true' and even the === ... but all give me the same error message.
Any insights on how to resolve this issue will be greatly appreciated.
I have such comparisons successfully before with integer values such as:-
window.onload= function show() {
if(<%=_CurrentUser.RoleKey%> == 1 || <%=_CurrentUser.RoleKey%> == 2)
document.getElementById('enr').style.visibility = "visible";
else
document.getElementById('enr').style.visibility = "hidden";
}
Do this:
if("<%=_CurrentUser.IsCTL%>" === "True")
<%=_CurrentUser.IsCTL%> is returning True. So wrap it with string and compare them instead. Notice the '===' instead of '=='.
In
if(<%=_CurrentUser.IsCTL%> == true)
I think <%=_CurrentUser.IsCTL%> is getting evaluated to True before the code is seen by the browser.
The browser will see this as
if(True == true)
True does not make a lot of sense to the browser, thats why the error. For this true to be treated as a boolean, try one of this:
if(new Boolean('<%=_CurrentUser.IsCTL%>') == true)
or
if(new Boolean('<%=_CurrentUser.IsCTL%>'))
This has gotten me before as well. ASP.NET will return True for a boolean which is true. You have to make it a string and then compare it to the string version == "True" in order to get a proper conditional statement.
Conversely, you could also just make a variable in javascript
var True = true;
You need to convert your native boolean value to the string "true" before output. So, assuming ASP.NET MVC, I believe it looks like:
<%=_CurrentUser.IsCTL ? "true" : "false"%>
I have had a lot of trouble with JavaScript and 'break' statements coming from a Ruby background.
Here is my function:
function isItTheNumber(numberToGuess){
if(previousGuess === null){
previousGuess = [playersGuess];
}
previousGuess.forEach(function(guess){
if(playersGuess === guess && previousGuess > 1){
textStatus.style.display = 'block';
textStatus.innerHTML = 'You already picked that number';
} else if(parseInt(playersGuess) === parseInt(numberToGuess)){
textStatus.style.display ='block';
textStatus.innerHTML = 'You Are CORRECT!';
} else {
previousGuess.push(playersGuess);
textStatus.style.display='block';
textStatus.innerHTML = 'You are ' + hotOrCold();
document.getElementById('guess-count').innerHTML = playerGuessCount++;
}
});
}
In my .forEach loop I would like to have a 'break' statement in my first if statement. I would like the loop to stop if it ever executes this block.
I realize I can't use a break statement in this forEach function after reading a few posts about it. I attempted the suggestion here using "every" but when I was using this wrapped in a function I was not able to return a true or false value.
I would like to avoid having to use any type of 'break' or hack for the break but will use it if it is the only way. If anyone has any suggestions on how I can re-work my logic or have any suggestions I would appreciate it. I'll list my logic in pseudo code below.
1) Check if the previousGuess array is null or populated. If it is null, set it to an array with the first value.
2) Iterate over the previousGuess array.
3) If: see if the user input (playerGuess) is in the previousGuess array. The previous guess
array must be larger than 1.
4) Else If: If the users guess is the same as the a the value, tell them they are correct.
5) Else: if the users guess isn't the same as the value, tell them and add 1 to the playerGuessCount.
The problem with my current logic is that the playerGuessCount is being invoked too many times. If the array is being iterated over and finds and the first if statement is true, it will still iterate over the rest of the array, adding 1 to the playerGuessCount even when they only submit 1 guess. The .forEach is strictly there to check if their guess is a repeat.
Here is my attempt with 'every' http://repl.it/P74
The .forEach method you are using is a wrapper implemented by extending a function prototype.
You can break out of a conventional loop:
for (var key in objs){
var obj=objs[key];
//do your business here
break; //this line exists the loop
}
However, if a callback function is used, you have to terminate the function call itself by placing a "skip" variable.
previousGuess.forEach(function(guess){
if (this.skip_the_foreach_loop) return;
if (need_to_exit) this.skip_the_foreach_loop=true;
});
Not the most efficient way but saves you a few CPU cycles.
Would this work for what you're trying to do?
function isItTheNumber(numberToGuess){
if(previousGuess === null){
previousGuess = [playersGuess];
}
// Using Array.prototype.every so a falsey return breaks
previousGuess.every(function(guess){
if(playersGuess === guess && previousGuess > 1){
textStatus.style.display = 'block';
textStatus.innerHTML = 'You already picked that number';
return; // returns undefined which is falsey and breaks loop.
} else if(parseInt(playersGuess) === parseInt(numberToGuess)){
textStatus.style.display ='block';
textStatus.innerHTML = 'You Are CORRECT!';
} else {
previousGuess.push(playersGuess);
textStatus.style.display='block';
textStatus.innerHTML = 'You are ' + hotOrCold();
document.getElementById('guess-count').innerHTML = playerGuessCount++;
}
return true; // Meaning go to next iteration
});
}
I wrote a simple html file with a textbox and submit button, and it generates and document.write's a response dependant on what you submit. I want to have it generate a response saying to enter content if the box is empty. The textbox's id is chatinput, so I have the following the code in the beginning
var chatinput_box=document.getElementById('chatinput');
var chatinput=chatinput_box.value;
Then a have a conditional, although I can't get it to work correctly; I've tried
if(chatinput==""){}
if(chatinput.length=0){}
if(chatinput=null){}
and others but none have worked correctly. Does anyone have another idea?
It should be this:
var chatinput = document.getElementById("chatinput").value;
if (chatinput == "" || chatinput.length == 0 || chatinput == null)
{
// Invalid... Box is empty
}
Or shorthanded:
if (!document.getElementById("chatinput").value)
{
// Invalid... Box is empty
}
The = assigns a value whereas == checks whether the values are equal.
Just offering an alternative, not trying to steal thunder ...
Create an isEmpty function to reuse on a variety of items.
function isEmpty(val){
return ((val !== '') && (val !== undefined) && (val.length > 0) && (val !== null));
}
Then you can apply it to whatever element you want:
if(!isEmpty(chatinput)){
// hooray its got a value!
}
Not exactly original, its the concept stolen from PHP, but it comes in handy a lot.