JavaScript Variable calls function, but stays undefined - javascript

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

Related

Botpress concatenate variable, as argument, in execute code action form

I know if I pass {{variable}} (like a {{event.text}}) in args field of action form works fine.
But, when I try concatenate this variable with a another String, this not work.
Result in {{state.api_url}}/users string, and I need http//myapi.com/users
Is it possible?
I may have an extremely kludgy workaround for this based on bad javascript.
I was looking to iterate a temp variable downwards. I did the assignment in the raw code box for a transition
Good code like temp.variable==1 would be a true/false test.
But just using one equals sign performs the assignment.
So temp.variable=temp.variable-1 in the raw code box subtracted one from my (numeric value) variable.
This seems to return False for the purposes of the transition so it doesn't matter where you point it as long as it's in the chain.
It seems to work for me, anyway.
I'm properly not sure what your code would look like, perhaps you make a new variable then do a transition with
temp.variable_you_just_made=state.api_url+'/users'
then call that variable doing your url thing?
[Looking around I come to suspect the correct thing would be to make a new action https://botpress.io/docs/10.0/getting_started/trivia_actions/ but I am new to all this]

Javascript: Array not shifting, multiple setTimeout functions (JSON)

I'm really stuck on this javascript question!
So I'm making a web page that will be completely animated (so it can be used for display for example in a television). That animation will be configurable by the user (stored in a database).
Right now, I've already made the code to store the configuration and to get the configuration (I do an AJAX call and save the configuration in an array of json objects) and everything is as it should be.
The problem is in the animation in which I go through the array and use setTimeout function to create animations. To iterate through the array I rotate it
(I use array.push(array.shift()) according to the answer here).
The first time the intervalmaster function is used, everything goes according to plan, but when the function is called again I need to rotate the array once more (because of the last animation) and the array just doesn't rotate!
Bellow I've left a portion of the code that I'm using that reproduces the problem I'm getting. I've also added the array jsonanima with some possible values (In reality the array is probably much bigger and with higher values).
I really don't understand what is happening, I've also considered that this could be a problem of the multiple setTimeout functions because I've read somewhere (couldn't find the link, sorry!) that is not really advised to use multiple setTimeout.
If that's the case is there any other way to do this?
Thank you in advance!
EDIT: Thanks to the comment from mplungjan I've realized that if change the console.log(jsonanimate) to console.log(JSON.stringfy(jsonanima)) it outputs the correct values (the json array rotated). This got me even more confused! Why do I need to JSON.stringfy to get the array in the correct order?!
Anyway, can't test this with the full code now as I'm not in the office, tomorrow I'll give more feedback. Thank you mplungjan.
EDIT2: Finally solved my problem! So the thing was the call to the function recursivegroup (recursivegroup(0);), this call was made before I rotated the array, so when restarting the animation the array would still have the incorrect values and every sub-sequential value was wrong.
A special thanks to mplungjan and trincot for the comments that helped me debug this problem.
Bellow I leave the code corrected so anybody with the same problem can check it out.
jsonanima=[{"VD":5,"A":10,"diff":0.25},{"L":7,"IE":8,"diff":0.25}];
function intervalmaster(flag){
function recursivegroup(index)
{
if(index==0)
{
//animateeach(jsonanima,0);
}
setTimeout(function(){
//HERE IT WORKS
jsonanima.push(jsonanima.shift());
console.log(JSON.stringify(jsonanima));
//animateeach(jsonanima,0);
//removed the if statement, since it was irrelevant as mplungjan noted
recursivegroup(index+1);
},(jsonanima[0]['diff'])*60*1000);
}
//Changed this
//recursivegroup(0);
var mastertime=0;
for(var key in jsonanima)
{
mastertime+=(jsonanima[key]['diff']);
}
console.log(mastertime,flag);
console.log(JSON.stringify(jsonanima));
if(flag==true)
{
jsonanima.push(jsonanima.shift());
console.log(JSON.stringify(jsonanima));
}
//changed to here
recursivegroup(0);
masterinterval=setTimeout(function(){intervalmaster(true)},mastertime*60*1000);
}
intervalmaster(false);

"in" operator showing functions in javascript

in my code I was always doing
for(i in vector)...
and it always worked, but the problem is that it somehow changed and now my for shows all the values but also the properties, like "remove" that is a function, and it is breaking my whole code.
I don't know why it suddenly changed, because I didn't do anything and I'm getting crazy with this already.
Do you guys know what is happening with my application?
Another thing is that the code only get this problem on my computer.
If I clone my repository again and try it works for while but then starts the problem again.
Thank you.
The in operator has always had this behaviour. Just check that the property exists directly on the object instead of on the prototype:
for (var i in vector) {
if (vector.hasOwnProperty(i)) {
// Property exists on object
}
}
That should solve your issues.
Tom

Comparing values in Array fails

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')

JavaScript string comparison fails randomly

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.

Categories

Resources