Keep losing incremental variable within for loop - javascript

I've been fiddling with this for way too long and can't seem to get it working as it should.
The problem I'm having is that I'm losing the value of my incremental variable in a for loop, specifically when it goes in to the if statement that I have inside of it. Ideally i want to iterate through an array until I find the correct value, attach a variable to that value and use it outside of the for loop. This is the structure of the array I'm working with.
var dXId = [
{url:"url1", dId:"id1"},
{url:"url2", dId:"id2"},
{url:"url3", dId:"id3"}
];
And here is the loop that I'm running everything through:
for(i=0; i < dXId.length; i++) {
if (dXId[i].url == currentUrl){
var dataXuId = dXId[i].dId;
break;
}
}
The incremental 'i' variable always reverts back to 0 within the if statement. It's odd, the dXId[i].url comes up correctly, but the dXId[i].dId pulls the first entry and 'i' seems to be lost after that. I'm sure there is a very simple solution to this, but javascript is something that I just always seem to have trouble with.

You are setting dXId[i].url = currentUrl inside your for loop instead of comparing with '=='. That could be part of the problem.
EDIT
As suggested by Eric...
The == Operator is to loosely compare the value of things, and the === is to strictly compare the value and type of things.
Examples:
Given x=10;
x == '10' // true
x == 10 // true
x === '10' // false
x === 10 // true

You have mistake in your if syntax.. you are assigning value of currentUrl to variable dXId[i].url
if (dXId[i].url = currentUrl){
...
}
It should be changed to === to compare string values.
if (dXId[i].url === currentUrl){
...
}
After that, it works! Example also here: js fiddle
Thus, it is rather funny that JavaScript lets do such things in the first place: Assigning value to a variable in if block should definitely not be allowed.
For example consider the following snippet:
var foo = 1, // change to 0 and console.log will not be displayed
bar; // undefined
// Assigning value of foo to bar
if (bar = foo){
// Will print out 1
console.log("bar is: " + bar);
}
Will result to a printing following output to the console:
bar is: 1
The reason being that if (bar = foo){ is equals to if (1){ which allows program to continue inside the if block :) ... if value of 0 is used for foo, console.log will not be displayed. (This is the behaviour at least which I tested using google chrome.)
Example about this in js fiddle

Related

How to Check the variable value is [""] in JavaScript

Example:
When I check a variable containing this value [""] it returns false.
var th=[]
th.push("");
if($("#multiselect").val()==th)
It returns always false.
Thank you.
Edit 1:
changed Var to var. It was a typo.
Edit 2:
Actually, the problem I faced was I was trying to get the value from a multi-select input. The multi-select input sometimes returns values as [""] even I haven't selected any values basically it's a plugin. So I was confused and I thought [""] is a fixed primitive value like 1, 10, "bla blah",.. So I tried to compare it with the same array as the right-hand side of the '=' operator.
It was stupid. Now I posted the solution to my problem and I explained my stupidity.
there are two things:
Change Var to var
You can use includes method of Array as:
var th = [] <==== chnage Var to var
th.push("");
if(th.includes($("#multiselect").val())) { <=== you can use includes method of array
// DO whatever you want
}
Make sure var is lowercased.
You are accessing th as an array, so you’ll need to specify the index of the value you are checking: th[0]
Use triple equals, too: .val()===th[0]
Double check the jquery docs if you’re still running into trouble.
Happy coding!
A couple of things to consider:
You have a typo in the code above; var is valid; Var is invalid.
Browser will aptly complain to solve this typo.
You are comparing an array to DOM value; this will always be false.
DOM is a costly process. Unless the value associated is dynamic, its better to read once, store value into a variable and continue processing instead of reading from DOM always.
You could choose to try something on these lines:
let arr = [1,2,3,4];
let domValue = $("#multiselect").val();
arr.push(5);
arr.map((el, ix) => {
if el === domValue return true; //or choose to do something else here.
});
var th=[]; //It is var not Var
th.push("");
if($("#multiselect").val()==th[0]) // change th to th[0]
I am unable to comment so having to use an answer for now. Are you trying to check if an array has any values? If so you can use
if(th.length){
// do something
}
If you want to check a normal variable for empty string you can simply use
if(th == “”){
//do something
}
I found the solution after a couple of days when I posted this question. Now I can feel how stupid this question was.
Anyway, I'm answering this question so it might help others.
Answer to my question:
When two non-primitive datatype objects(which is the Array here) are compared using an assignment operator, it compares its reference of the object. So the object creation of both arrays would be different. If I want to check the array has [""] value, I should do something like the below.
function isArrValEmptyCheck(value) {
return !value || !(value instanceof Array) || value.length == 0 || value.length == 1 && value[0] == '';
}
console.log(isArrValEmptyCheck([""]));//returns true
console.log(isArrValEmptyCheck(["value1"]));//returns false
Sorry for the late response. Thanks to everyone who tried to help me.

what would happen if you use two equals rather than only one in your execution block after an if conditional in JavaScript?

I am still learning, so I'm sorry if my question is not well formatted.
I was trying to write a function to insert a word to a string in a specified position, however I made a mistake which is writing two equal signs == rather than one in the execution block and this resulted in wrong output when tested.
However, I already know that the execution of code after if/else needs to not be boolean and I noticed this typo and I corrected it by removing one equal sign and the function worked perfectly fine but I was just left wondering why have I never questioned the significance of strictly having one equal sign when executing code after if conditionals.
so here is the wrong code:
function insert(original,to_insert,position){
if (to_insert == "undefined" && position == undefined){return original;}
else if (position == undefined){position == 0}
var x = original.slice(0,position);
var y = original.slice(position);
console.log(x + to_insert + y);
}
insert('We are doing some exercises.','JavaScript ');
//Wrong output >>>> "We are doing some exercises.JavaScript We are doing some exercises."
insert('We are doing some exercises.','JavaScript ', 18);
//correct output>>>> "We are doing some JavaScript exercises."
and here is the correct code:
function insert(original,to_insert,position){
if (to_insert == "undefined" && position == undefined){return original;}
else if (position == undefined){position = 0}
var x = original.slice(0,position);
var y = original.slice(position);
console.log(x + to_insert + y);
}
insert('We are doing some exercises.','JavaScript ');
//correct output >>>> JavaScript We are doing some exercises."
insert('We are doing some exercises.','JavaScript ', 18);
//correct output>>>> "We are doing some JavaScript exercises."
would you please explain what happens inside my wrong code, like what causes the function to not run properly when booleans were used, obviously the function runs once at a time, so what difference would an absolute value of position make compared to a variable value of position.
Thanks in advance
else if (position == undefined){position == 0}
In your wrong code, position remains undefined since you did not do an assignment, you simply checked if position (which is undefined) is equal to 0
So, when you did var x = original.slice(0,position); slice() simply ignored the 2nd argument, which in this case is undefined and sliced from start to end, which is the default behaviour in case the 2nd argument is not used.
From MDN:
The slice() method extracts a section of a string and returns a new string.
str.slice(beginSlice[, endSlice])
endSlice
Optional. The zero-based index at which to end extraction. If omitted, slice() extracts to the end of the string. If negative, it is treated as sourceLength + endSlice where sourceLength is the length of the string (for example, if endSlice is -3 it is treated as sourceLength - 3).
In your case, since you pass undefined (because position == undefined), it's like you omitted it
One equal is to assign values to variables, two equals are for camparing two variables. This is the simplest way to explain it.
= - assigning operator
== - comparing operator
if (position == undefined){position == 0}
This mean if your position is undefined position must be 0. Like it should be 0 but you are not defining it. Two equals is usually use to do comparution actually : does position is equals to 0
However one equal mean you assign the value 0 to position.
I can see two problems in your code.
if (to_insert == "undefined" && position == undefined){return original;}
Here you are checking if to_insert is equal to the string "undefined", but not undefined.
else if (position == undefined){position == 0}
Writing position == 0 will just return a boolean. So in this case, it'll return false (because it execute only if position == undefined returns true).
So it's like if in your code, you had a false between two lines, and you don't change the value of any variable.
else if (position == undefined){position = 0}
By writing only one =, you assign the value 0 to the variable position.
So, when you call the slice() method, the second argument is still undefined, so the method ignore it and just slice the string to the end.
Hope I helped you understand !
You're essentially asking, "What is the difference between using one equals sign (=) and using two equals signs (==)?"
Assume we have the following initialization for both examples:
var pikachu_hp;
One equality sign (=):
pikachu_hp = 50;
This sets the variable, pikachu_hp, to have the Number data type with a value of 50.
Two equality signs (==):
pikachu_hp == 60;
This compares the value (not data type, that's three (===) equals signs in JavaScript) of pikachu_hp against what is on the right hand side; in this case, that's the Number 60. If pikachu_hp has a data value of 60, the expression returns true. If pikachu_hp has a data value of anything else but 60, the expression returns false. Again, I call this an "expression" because it does not equate to anything; it represents either a true or false value.

JavaScript Short Circuit Logic

After seeing some examples online, I've collected two different explanations:
Ex: var x = A || B;
If A exists and B does not, left side is returned.
If A exists and B exists , return right side (last evaluated value).
Based on that logic, I would assume that x would return: v.item(0).click(). But when testing it x first returned B then A, aka fired B then fired A as well. Why? (http://jsfiddle.net/nysteve/QHumL/59/)
HTML:
<div class="indeed-apply-button" onclick="alert('BOOM BUTTON');">boo</div>
<div class='view_job_link' onclick="alert('BOOM LINK');">boo</div>
JavaScript
var v = document.getElementsByClassName('view_job_link');
var i = document.getElementsByClassName('indeed-apply-button');
var x = v.item(0).click() || i.item(0).click();
EDIT 1:02 PM 10/10/2013
Did not mention my true intentions, but based on the answer and discussion, my goal was essentially to convert the following piece of code into the JavaScript code I originally mentioned.
var v = document.getElementsByClassName('view_job_link');
var i = document.getElementsByClassName('indeed-apply-button');
if(v){v.item(0).click();}
else if(i){i.item(0).click();}
else{}
In the code above, how would you read if(v){v.item(0).click();} vs. the short-circuit?
Neither of your two descriptions are accurate.
var x = A || B;
What that does is:
Evaluate "A". Call the result VA.
If VA is not null, undefined, 0, NaN, false, or the empty string, then the value of the overall expression is VA and evaluation stops.
Evaluate "B". Call the result VB. That value, VB, is the value of the expression.
Your test code first tests the return value of calling the "click" function on the first element and then the second. Those functions both return undefined, so the subexpressions on both sides of the || are evaluated. That is, the first call gets VA and it's undefined, so that means that the other side will be evaluated too, and that'll be the value of the expression. (It's going to come out undefined.)
edit — OK now that you've added more to the answer, I think I see what you're up to.
In your actual code (or, I guess, the sample code that's closer to reality), you've got:
if(v){v.item(0).click();}
else if(i){i.item(0).click();}
else{}
That means something quite different than:
var x = v.item(0).click() || i.item(0).click();
Note that in the if statement version, it's explicitly checking "v". A test like that will perform a "truthy/falsy" test on the value of "v". In this case, it's really checking to make sure that "v" isn't either null or undefined. In the || version, however, there's no such explicit test for the "goodness" of variable "v"; it's just used directly. (If it happens to be null there, that'd result in a runtime error.)
A version of the actual code using || and && is possible, but in my opinion the existing code is clearer. However, just for discussion purposes, you could replace the if version with:
v && (v.item(0).click(), true) || i && i.item(0).click();
Personally I think that looks kind-of ugly.

JavaScript: an if statement is changing outcomes of a random generator?

Basically I'm creating a program similar to a blackjack program where two cards are dealt according to a random number generator, with the possibility of the same card being dealt twice at the same time (i.e. two Queen of hearts showing up at once) and I want to create a counter of how many times that event occurs, but when I implement an if statement, it affects the outcome so that the two cards are ALWAYS the exact same...can someone tell me what I'm doing wrong here? The code is as follows:
function dealHand() {
var randomCardOne = Math.floor ((Math.random() *13) +2);
var randomCardTwo = Math.floor ((Math.random() *13) +2);
if (randomCardOne = randomCardTwo) {identicalCards()};
}
var identicalPairs = 0;
function identicalCards(){
document.getElementById("identical").value=++identicalPairs;
}
You are assigning the value of one card to another
if (randomCardOne = randomCardTwo) {identicalCards()};
should be
if (randomCardOne == randomCardTwo) {identicalCards()};
In the first case you are simply evaluating if randomCardOne is "truthy" after being asigned the value of randomCardTwo.
Consider if you might want to use === instead of == since
2 == '2' // yields true
2 === '2' // yields false
It's not an issue in this case but it might be in others so it's good to be aware of this. I try to stick with === since it is more strict.
You're using =, that's an assignment operator in JavaScript. You should be using ==
e.g.
if (randomCardOne == randomCardTwo) {identicalCards()};

If statement throwing error for nonexistent object

The answer to this question seems like it would be obvious, but I'm always looking to improve my semantics, so bear with me.
I have an array structure with individual items containing X,Y coordinates
var example = new Array();
example.push({x:0,y:0});
In my code I have a set interval that updates my canvas and checks for certain conditions. Including one similar to this
if(example[0].x == other.x && example[0].y == other.y)
{
//do something
}
The issue is that the array is very dynamic, and when the code is first executed the example array is empty. Hence, Chrome throws errors along the lines of "Cannot get property x". To shut up the console, I added a dummy item to the array {x:"~", y:"~"} but it seems really unintuitive. Have I implemented an undesirable data structure? What's a simple way to handle if statements for objects that... don't exist?
Why don't you just check whether the array has elements?
if (example.length && ...)
Or whether the first element is true:
if (example[0] && ...)
if (0 in example
&& example[0].x == other.x && example[0].y == other.y) {
// do something
}
(This works for arbitrary index, not just 0; if you just want to check if the array is non-empty, example.length as shown by melpomene is good.)
You should be able to check on the first-level element (i.e. 'example') - JavaScript usually throws errors like this when you try to access a property of an element that is null or undefined. Like some others have already shown:
if(example[0] && example[0].x === other.x)
The point is though that JavaScript will let you have example[0] and return as you like, but once you try to access that property, you're out of luck:
var example = [];
//undefined
example
//[]
example[0]
//undefined <--- this is a falsy value, will evaluate false in a check
example[0].x
//TypeError: Cannot read property 'x' of undefined

Categories

Resources