I’m having a pretty weird bug occurring in my JS application on a random basis. Basically, the script fails to accurately compare two strings. More specifically, at times does not see two identical strings as identical: ('blah' == 'blah') returns false.
The funny thing is that on another try, the same two strings may be admitted to be identical (statement returns true). I never managed to figure out the pattern. I’ve also tried to use === instead of ==; this didn’t help.
I couldn’t think of a better way to demonstrate and prove this ridiculous bug other than by recording a screencast. So here it is: http://www.screenr.com/klOs. I keep giving correct answers for each quiz in that video, but closer to the end you will how my answers for ‘Japan’ and ‘Taiwan’ will be regarded as ‘wrong’; the console will also show the given answer string, the correct answer string, and the result of their comparison (false ?!!).
So what could possibly be the reason for this odd behaviour and how do I get around fixing it?
You can see the code with the comparison statement in the screencast. The ‘params.givenAnswer’ comes directly from the button text label:
//*** Options for answering the card quiz
quizOptions = new Ext.Panel({
id: 'quizOptions',
[…………]
listeners: {
el: {
scope: this,
tap: this.checkAnswer
}
}
});
checkAnswer: function(container, element) {
// Get the text value of the button clicked
var answer = Ext.fly(element).dom.innerText;
Ext.dispatch({
controller: 'Practice',
action: 'checkAnswer',
givenAnswer: answer
});
},
UPDATE Thank you #JAAulde and #Mike! I’ve tried to include the quotes and the var type in the logging and I got this result:
Now it’s clear why the string comparison fails: there seem to be an extra line break of sorts in the first string. It’s still very weird, since it didn’t not appear as a blank new line in the previous logging, and most importantly, it appears there randomly (notice how ‘Taiwan’ was accepted this time without any problems).
I’ve included a simple line-break removal rule for the answer strings, and now everything seem to be working fine. Thanks a lot everyone!
Using === is a strict equality comparison. This means that the data type and the contents are being compared. They both (data and type) must be the same to equal and return true.
When you switched your strict comparison to == the test should have worked even though the data types were different. It failed however because of the extra blank spaces.
Related
I'm extremely new to JavaScript and am attempting to make a very simple game of 'Rock, Paper, Scissors' that is played through the console.
Here is a jsfiddle.net link to the full thing.
The main issue so far is that, every single round, the game will result in a Tie (another one is that incorrect inputs in humanTurn() lead to an error further down the line, but that's not relevant to this topic which I feel is more pressing).
Both humanTurn() and computerTurn() seem to work fine when called individually, however when called within gameRound(), the two console.log()'s (lines 36 and 38) don't seem to be returning a value of any kind, and in the console these show up as ƒ toLocaleUpperCase() { [native code] }. I tried searching for what this could mean, and the only conclusion I've been able to come up with so far is that no value is actually being stored inside of the two variables, AIChoice and HUChoice, and I cannot fathom a reason for why this would be happening.
Any and all help is greatly appreciated!
computerTurn().toLocaleUpperCase and userTurn().toLocaleUpperCase are both functions and since they are on the String prototype, they are both the same function. If you compare them, they will always be equal.
You need to actually call the function in order to get the values you want:
let AIChoice = computerTurn().toLocaleUpperCase();
console.log(AIChoice);
let HUChoice = humanTurn().toLocaleUpperCase();
console.log(HUChoice);
I am solving curious problem right now. I am testing a string with regexp and it returns false eventhough it should return true. I am implementing it in javascript. I have this function
function isPhoneNumberValid(phoneNumber) {
return /^\+\d{12}$/.test(phoneNumber);
}
phoneNumber is a variable in format of + and 12 numbers after (+421123123123 for example). I've played around with different versions of regexp like /^\+[0-9]{12}$/.
According to sites like https://www.regextester.com/21 my regexp should be working for the format I want, yet it returns false still. When I tried testing this regexp /^\+[0-9]/ it returned true when only +3 was written, I guess the problem is with the numbers count?
Parameter phoneNumber received in the function is correct one so I don't think the mistake is there. Also no combination of modifiers helped.
Here is a log of this function
function isPhoneNumberValid(phoneNumber) {
console.log('ph:'+phoneNumber);
console.log(/^\+\d{12}$/.test(phoneNumber));
}
To give you more insight I have a input type text with class .phoneNumber, then I have jquery function watching keyup event, it looks like this
$('.phoneNumber').on('keyup', function() {
if (isPhoneNumberValid($(this).val())) {
console.log('is valid');
} else {
console.log( 'invalid');
}
});
Other function you've already seen above. I tried wrapping values in String(), too.
I am trying to clarify why live example in online environment is for no good, since I know this code works in there as I already stated before. The question is aimed more to what could possibly make it go this way, since the exact same copy works in codepen, yet doesn't work in my project.
The problem was with latte template engine. It needed to have
<script n:syntax="double"></script>
to work.
I'm a beginner in jquery and ajax. While i was going through some example online, i came across the following piece of code and wondered what exactly it does.
lines = newLine.split('#');
jQuery.each(lines, function(lineNo, line) {
eval("linedata = " + line);
data.push(linedata);
});
I'm not a programmer, but just trying to understand its functionality. Can anyone help me?
The each function iterates over an array which is supplied as the first parameter. During each iteration the index and element are passed into a function that is performed. The function is passed as the second parameter to the each function.
Read more on the jQuery Documentation
In the example you have provided a string newLine is split into an array using # as the delimiter.
The each function then iterates over the newly created array, assigning the value of each element to a variable linedata and pushes linedata onto another array.
This could be more easily achieved with the following, since the call to eval is unnecessary:
jQuery.each(lines, function(lineNo, line) {
data.push(line);
});
I pretended, for a moment, that I was a new programmer. This is how you should go about looking into things from here on out:
1.) Ok, I don't know what this first line is doing. It's splitting something (based on the split word). Hmmm let's Google for "split javascript". This is the first thing that comes up. From here, you may be wondering what a String is, so you would search for that as well).
2.) Ok so now I know that splitting a String gives me an array (again you probably looked this up by this step) of the newLine substrings that were separated by the # character. Cool. So let's look into what jQuery.each does. I google "jQuery.each" and this is the first thing that comes up.
Awesome! Now you understand what a String is, an Array, the split function from String as well as what jQuery.each is. :D
EDIT: As you move forward, you'll realize that W3C is generally an inferior source of information. I simply linked to it since it was literally the first thing that came up when I Googled "split javascript". Overall it does the job for giving you a good overview of certain things when you're learning them for the first time.
Sometimes comparing two strings within arrays fails. Failing occurs occasionally only in looped ifs. Example code below stands for implementing the problem.
searchTable.sort();
for(n=1;n<searchTable.length;n++){
// alert(searchTable[n-1]!=searchTable[n]);
if(searchTable[n-1]!=searchTable[n]){
idx++;
memTable[idx]=searchTable[n];
}
}
Values in the searchTable are strings for sure, and all values are not similar either.
In loop, all values are set in memTable[idx], despite of the similar values in [n-1] and [n]. Activated alert() shows the right comparison result, but if passes all through. Looks like the comparison in if is done by reference, not by value. How is this possible? Is this a bug in the JavaScript interpreter or what?
Action can be corrected by adding valueOf()-methods to both members in comparison expression. I've crashed this failier whithin looped ifs only. Sometimes it takes a long time to figure out why the code won't work.
You seem to have concluded that the problem is related to the actual data in the arrays. I suspect we can't help more specifically without seeing what that data is.
If putting valueOf() in front makes it work, then you can code a check for when the comparison with valueOf() is different than just straight != and output the two values to the debug console or break into the debugger so you can inspect what values are causing the problem. In other words, write code that catches the problem condition and allows you to inspect it.
Looks like you want to remove double values from an Array.
Try using:
var tmpObj = {}, resultArr = [];
for(n=1;n<searchTable.length;n++){
if (searchTable[n] in tmpObj){
continue;
}
tmpObj[searchTable[n]] = true;
}
for (var l in tmpObj){
resultArr.push(l);
}
Note: this will not differentiate between Numbers and Strings (so 1 equals '1')
Here is a simple chunk of code:
1 var selected_clone = selected.clone();
2 alert(selected_clone.text());
3 var new_value = selected_clone.text();
4 form_li.find('input.ajax_selection').val(new_value);
Now.
Line 2 (debugging) outputs exactly the value I expect it to.
Line 3 is redundant, I know, but I used it for testing: when passing an arbitrary string to new_value, the val in line 4 works perfectly.
It does not change the value if I assign it the result of selected_clone.text()
The question is: why does it behave in such a puzzling way?
From chrome's debugging console, just chilling silence.
Additional info:
typeof(new_value) is string;
the value in the form field is actually updated: the value attribute, however is not.
about the latter point: no, it's not my debugger. the values sent on submit are non-updated.
the request sends the unupdated value; while the form displays the updated one.
Holy Shitzu this is weird.
I solved the problem by changing line 4 to: form_li.find('input.ajax_selection').attr('value',new_value);.
That does not make the slightest amount of sense to me though, and I would still like to know why.
The answer to your new question can be found in that question: .prop() vs .attr()
To understand you will need to know that val() is a shortcut to prop('value')
I would first try to know how many objects the form_li.find(...) method returns. Then I would check if
form_li.find('input.ajax_selection').attr("value",new_value)
works or not. Difficult to answer with so few code, sorry