Equality testing in Javascript - javascript

just trying to test for equality in this piece of code, but getting a fail.
<input type="text" name="dave_blah"/>
<input type="text" name="dave_bleh"/>
I then access the name values of each of these inputs and assign them to two variables, name1 and name2. I then extract the first part of the name,delimited by a "_".
var oldName = name1.name.split('_',1);//dave
var thisName= name2.name.split('_',1);//dave
alert(oldName);
alert(thisName);
if(oldName !== thisName){//if "dave" is not equal to "dave"
alert("name difference = "+ oldName + " " + thisName);
}
Yet, when running this code, the message alerts regardless (I've tried != too). In principle, the alert shouldn't execute. It's quite late in the evening, so it's probably obvious, but can someone point this noob in the right direction? If I remove the not operator from the if statement - the function works as desired.

thisName and oldName are both arrays, do something like this:
var oldName = name1.name.split('_',1)[0]; //dave
var thisName= name2.name.split('_',1)[0]; //dave
And I think it should work.

OK. I've sussed the problem. The comparison was seeing the participants in the test both as Objects, as opposed to the string value of the contents. So, I solved it by casting the results to a string.

Related

How to access the first two digits of a number

I want to access the first two digits of a number, and i have tried using substring, substr and slice but none of them work. It's throwing an error saying substring is not defined.
render() {
let trial123 = this.props.buildInfo["abc.version"];
var str = trial123.toString();
var strFirstThree = str.substring(0,3);
console.log(strFirstThree);
}
I have tried the above code
output of(above code)
trial123=19.0.0.1
I need only 19.0
How can i achieve this?
I would split it by dot and then take the first two elements:
const trial = "19.0.0.1"
console.log(trial.split(".").slice(0, 2).join("."))
// 19.0
You could just split and then join:
const [ first, second ] = trial123.split('.');
const result = [ first, second ].join('.');
I have added a code snippet of the work: (explanation comes after it, line by line).
function getFakePropValue(){
return Math.round(Math.random()) == 0 ? "19.0.0.1" : null;
}
let trial123 = getFakePropValue() || "";
//var str = trial123.toString();
// is the toString() really necessary? aren't you passing it along as a String already?
var strFirstThree = trial123.split('.');
//var strFirstThree = str.substring(0,3);
//I wouldn't use substring , what if the address 191.0.0.1 ?
if(strFirstThree.length >= 2)
console.log(strFirstThree.splice(0,2).join("."));
else
console.error("prop was empty");
Because you are using React, the props value was faked with the function getFakePropValue. The code inside is irrelevant, what I am doing is returning a String randomly, in case you have allowed in your React Component for the prop to be empty. This is to show how you an create minimal robust code to avoid having exceptions.
Moving on, the following is a safety net to make sure the variable trial123 always has a string value, even if it's "".
let trial123 = getFakePropValue() || "";
That means that if the function returns something like null , the boolean expression will execute the second apart, and return an empty string "" and that will be the value for trial123.
Moving on, the line where you convert to toString I have removed, I assume you are already getting the value in string format. Next.
var strFirstThree = trial123.split('.');
That creates an array where each position holds a part of the IP addrss. So 19.0.0.1 would become [19,0,0,1] that's thanks to the split by the delimiter . . Next.
if(strFirstThree.length >= 2)
console.log(strFirstThree.splice(0,2).join("."));
else
console.error("prop was empty");
This last piece of code uses the conditional if to make sure that my array has values before I try to splice it and join. The conditional is not to avoid an exception, since splice and join on empty arrays just returns an empty string. It's rather for you to be able to raise an error or something if needed. So if the array has values, I keep the first two positions with splice(0,2) and then join that array with a '.'. I recommend it more than the substr method you were going for because what if you get a number that's 191.0.0.1 then the substr would return the wrong string back, but with splice and join that would never happen.
Things to improve
I would strongly suggest using more human comprehensible variables (reflect their use in the code)
The right path for prop value checking is through Prop.Types, super easy to use, very helpful.
Happy coding!

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.

JavaScript indexOf() Method giving -1 when decimal value is present in array

I'm having some trouble with the JavaScript indexOf() Method. I have an array...
pointLatArray = new Array();
When I try to get the index of a variable that I know is present in the array it returns -1, which I know normally indicates to the value not being found. When my code is as follows..
setlat = 52.6688391881732;
pointArrayIndex = pointLatArray.indexOf(setlat);
console.log(setlat + " " + pointLatArray[8] + " " + pointArrayIndex);
I get the following logged to console.....
04-16 12:35:31.370: D/CordovaLog(7048): 52.6688391881732 52.6688391881732 -1
However when I change the code by replacing setlat with pointLatArray[8] in the following line....
pointArrayIndex = pointLatArray.indexOf(pointLatArray[8]);
the following gets logged to console where it displays the correct index of 8 instead of -1 as expected.......
04-16 12:46:17.230: D/CordovaLog(8497): 52.6688391881732 52.6688391881732 8
Is it because I'm using such a long decimal set as the variable setlat? If so, or for what ever reason if anyone could suggest a fix I would appreciate it very much.
Many thanks
Strict comparison for double numbers is not a good idea. Probably what you observe here is rounding error. Although the numbers seem to be the same to you they may differ by a small epsylon.
One option I see is to use custom indexOf function using epsylon comparison(i.e. allow numbers to differ by a small value. For instance 0.000000000001 or 1e-12).

What is the ??! operator in Javascript?

when I'm looking for some sites Javascript code, I see this
function hrefLeftMenu() {
var x = true;
for (i in info) {
$(".leftmenu ul").append("<li" + (x ? " class='active'" : "") + " onclick='openAnInfo(\"" + i + "\", this);'> - " + info[i].title + "</li>");
x = x??!x;
}
openAnInfo("0", ".lelelesakineyy");
}
What it does in javascript? Why the coder's used this operator?
Thanks.
What it does in javascript?
It throws a syntax error.
> x = x??!x;
SyntaxError: Unexpected token ?
Why the coder's used this operator?
Taking a reasonable guess (beyond "they made a mistake") would need more context. Saying for sure would require mind reading :)
In JavaScript this is not valid code. However, the sequence ??! exists (existed?) in C as a trigraph, representing |. Maybe that's not JavaScript code, or it was poorly-ported from ancient C code. But even then, x = x | x can hardly be called a useful statement.
EDIT: With a bit context in the question now, that speculation is likely wrong. A friend suggested that maybe the sequence x?? was a typo and subsequent attempt to correct it where backspace was turned into a character by some intermediate mangling (not uncommon when typing in terminals or via SSH) and that the line in question was supposed to be x = !x.
I think it is a mistake. They're generating a menu and x is used to set an item as active, and it looks like they want to default to selecting the first item. They want x to be true the first time around, and then false for the rest. It was probably supposed to be something like
x = x?!x:x; // If first time through, then set x = false for the rest
aka
x = false; // Set x = false for the rest
but confusion/muddy thinking led to over-complification.
Was this a mistake?
Did you mean this?
x= x?x:!x;

Javascript unable to assign value to variable and causes break --> word5 = (keywords[n].length);

Doing some javascript self-learning and the program itself is very simple. It searches through the input for keywords and when it finds it, it places the index values into list placeholders. (I'll develop later code to remove repetitions).
However, a snag. I'm trying to do something very simple. All I'm doing is assigning the variable words5 to keywords[n].length. Now I've discovered the keywords[n].length does print me the correct value when nested into document.write(). I've also discovered that keywords[n] also prints the correct value when nested into document.write(). BUT if either are used in the code outside of a document.write, it causes the code to break.
Been going at it for hours. And I haven't been able to find a solution. Do you guys have any clues? The code that I used to test it out is commented out.
<html>
<body>
<script type="text/javascript">
function separate()
{
contents = document.myForm.event.value;
placeholders = [32342423, 253234523];
keywords = [" in ", " at ", " on ", " for "];
for(n=0;n<=keywords.length;n++)
{
for (i=0;i<=contents.length;i++)
{
//document.write(i,"+", i+keywords[n].length, keywords[n])
//document.write(keywords[n].length)
word5 = (keywords[n].length);
//document.write(" " + contents.slice(i,i+word5) + " ")
//if (contents.slice(i,i+4) == " at ")
//if (contents.slice(i,i+wordlength) == " at ")
//if (contents.slice(i,i+4) == keywords[n])
if (contents.slice(i,i+word5) == keywords[n])
{
placeholders.push(i);
}
}
}
document.getElementById("sliced").innerHTML = placeholders;
printer();
}
function printer()
{
contents = document.myForm.event.value;
document.getElementById("MSG").innerHTML = contents;
}
</script>
<form name="myForm" method="post">
Add Event: <input type="text" name="event" value="Whatever at hello at crazy" /><br />
<input type=button value="Submit" onClick="separate()" />
</form>
<SPAN ID="sliced"> </SPAN>
<p></p>
<SPAN ID="MSG"> </SPAN>
</body>
</html>
Any help is greatly appreciated. Saviours really =)
The eror I get when I run your code is that:
wordlength is undefined
This is causing the code to fail. Where are you defining wordlength?
Update
Also be aware that when you're looping through arrays that arrays have a zero index. That is, the first item in the array is item 0. The count of the number of items in the array is always going to be greater than the sum of the indexes (index sum + 1).
This basically means that when you use the <= (less than or equel to) operator in your for loop, you're looping from zero to the number of items in your collection, however, since your array index begins are zero, you're eventually going to be requesting an item from your array that doesn't exist.
To ensure that you only loop over the available items use the < operator rather than <=.
that's not what's breaking your code, it seems like you are not defining the variable "wordlength" anywhere on your code, this is what's breaking your code.
word5 = (keywords[n].length) actually works.
Also I would recommend getting "firebug" addon for firefox, it's the best way to debug any javascipt or html code, use the console to output your debug statements using "console.log(myvar)" instead of document.write which is a pretty old fashioned way of doing things.
Let me know if this solution doesn't work for you :)
EDIT:
I did another set of tests and found out what the reason was, your first loop is running 1 more than what your current number of arrays are, so instead of making it "less than or equal too" it should just be less than:
for(n=0;n<keywords.length;n++)
Hence why you're getting a keywords[n] is undefined, as there is no keywords[4] in the array

Categories

Resources