I have an image I'm trying to shake when a user guesses the name of a fish wrong. I'm using a conditional ng-class="{'shake':error}". However, even when the answer is correct the image shakes. I don't believe that at anytime $scope.error is set to true. What am I missing here?
codepen
I think what you want to do is return guessIsCorrect or guessIsWrong from your compare function.
$scope.compare = function(guess) {
guess = guess.replace(/\s/g, '').toLowerCase();
var answers = [];
answers.push($scope.name.replace(/\s/g, '').toLowerCase());
currentAnimal.alts.forEach(function(alt) {
answers.push(alt.toLowerCase().replace(/\s/g, ''));
});
//console.log(answers);
//console.log("Guess: " + guess + "\n");
//console.log("Answer: " + answers + "\n");
for (var x = 0; x <= answers.length; x++) {
if (guess === answers[x]) {
return guessIsCorrect();
}
if (x === answers.length) {
return guessIsWrong();
}
}
};
Related
I am trying to make a simple game, in the below function handCricketBat(), the if conditional statement is getting skipped even when the condition batsMan = bowlerMan is satisfied. It always moves on to the else statement. Can someone tell me why this is happening.
function handCricketBat(){
var total = 0;
for (x = 1; x <=6; x++){
var batsMan = prompt("Ball " + x + " \nEnter Between 1-6");
var bowlerMan = randomBall();
console.log("The bowler - "+ bowlerMan);
if (batsMan === bowlerMan) {
console.log("Howzattt");
break;
}
else if (batsMan !== bowlerMan) {
console.log("That's good batiing, scoring a " + batsMan);
continue;
}
total += +batsMan;
}
console.log(total);
}
function randomBall(){
return Math.floor(Math.random()*7);
}
Your batsMan is a string.
Use var batsMan = parseInt(prompt("Ball " + x + " \nEnter Between 1-6")); instead and it should work.
I actually want to update my previous question Javascript understanding return because the code below is quite similar to the previous one but since that question was answered already I decided to post this. The code of my previous questions works fine already but I want to satisfy some of my curiosities so I experimented the code and moved the return namePosition,
function positionIdentifier(name, nameArray) {
var namePosition;
for (i = 0; i < nameArray.length; i++) {
if (nameArray[i] == name) {
namePosition = function() {
alert("Your name is in position number " + (i + 1));
}
}
}
return namePosition;
}
name1Array = ["look", "sky", "walk", "kier"];
positionIdentifier("walk", name1Array)();
Why does it alert the wrong position (i+1)? Instead it alerts the final position which is the length of the array.
You forgot to use break statement here is correct code:
<script>
function positionIdentifier(name, nameArray) {
var namePosition;
for (i = 0; i < nameArray.length; i++) {
if (nameArray[i] == name) {
namePosition = function () {
alert("Your name is in position number " + (i + 1));
};
break;
}
}
return namePosition;
}
name1Array = ["look", "sky", "walk", "kier"];
positionIdentifier("walk", name1Array)();
</script>
That my friend is what is called a closure in javascript.
function() {
alert("Your name is in position number " + (i + 1));
}
When positionIdentifier function is invoked, i has the last value from the for loop.
To fix this you need to do this
function positionIdentifier(name, nameArray) {
var namePosition;
for (i = 0; i < nameArray.length; i++) {
if (nameArray[i] == name) {
/* now this will keep the correct value of i */
namePosition = (function(i) {
return function(){
alert("Your name is in position number " + (i + 1));
}
})(i)
/* now this will keep the correct value of i */
}
}
return namePosition;
}
Here is a working fiddle https://jsfiddle.net/uxyot51b/
I was doing a cookie practice in javascript and developed the following code:
function getCookie(kname) {
var fullkeyname = kname + "=";
var fullcookie = document.cookie;
var acookies = fullcookie.split(";");
for (var i = 0; i < acookies.length; i++) {
var cookie = acookies[i];
while (acookies[i].charAt(0) == " ") { //THE ISSUE IS HERE
cookie = cookie.substring(1);
}
if(cookie.indexOf(fullkeyname) == 0) {
return cookie.substring(fullkeyname.length, cookie.length);
}
}
return "";
}
It didnt worked and seemed to rise and infinite loop so I tracked my code with "document.write" in various parts and discovered that if I change the "while" condition it will work as follows:
function getCookie(kname) {
var fullkeyname = kname + "=";
var fullcookie = document.cookie;
var acookies = fullcookie.split(";");
for (var i = 0; i < acookies.length; i++) {
var cookie = acookies[i];
while (cookie.charAt(0) == " ") { //RIGHT HERE
cookie = cookie.substring(1);
}
if (acookies[i].indexOf(fullkeyname) == 0) {
return cookie.substring(fullkeyname.length, cookie.length);
}
}
return "";
}
Now my code works as expected, however I dont know why, since I have set the value of cookies to "cookie=acookies[i]" I dont understand why it should loop indefinetly if I dont use the "cookie" variable.
Question is: why does the code works with my "cookie" variable and not with the "acookies[i]" even though the sould have the same value at that given moment?
It causes an infinite loop because you are checking if the first character of acookies is an empty space, then if it is, you are removing the first character of cookie (NOT acookies). Therefore, if acookies does have a space as the first character, the while statement will always be true because you aren't removing that space from acookies
function getCookie(kname) {
var fullkeyname = kname + "=";
var fullcookie = document.cookie;
var acookies = fullcookie.split(";");
for (var i = 0; i < acookies.length; i++) {
while (acookies[i].charAt(0) == " ") { //THE ISSUE IS HERE
acookies[i] = acookies[i].substring(1); // FIXED THIS LINE
}
var cookie = acookies[i];
if(cookie.indexOf(fullkeyname) == 0) {
return cookie.substring(fullkeyname.length, cookie.length);
}
}
return "";
}
edited for typo, thank you FREE_AND_OPEN_SOURCE
I see a problem in while loop
while (acookies[i].charAt(0) == " ") { //THE ISSUE IS HERE
cookie = cookie.substring(1);
}
once acookies[i].charAt(0) == " " becomes true, it will keep on looping and will never get to go outside while loop to increment the value of 'i'.
and in the second version of the code you're modifying the cookie variable itself which make the while condition false which moves the control out of the loop and continue execution.
I can't seem to get data from my taffyDB.
It has to be bad syntax but I don't know where.
My Javascript looks like this:
// init db
var procTech = TAFFY();
//..... other code in the middle
procTech().remove();
var x = 0;
$(".sxRow select[id^='KRCtech_']").each(function() {
var techName = $(this).val();
x++;
var xStr = x.toString();
clog(xStr + " " + techName);
procTech.insert({"count":xStr,"tech":techName });
});
var ret = eval(procTech().select("count","tech"));
clog(ret.length);
for (j = 0; j <= ret.length - 1; j++) {
clog("read back: " + [j][0] + "," + [j][1]);
}
// wrapper for console.log
function clog(s) {
window.console && console.log(s);
return;
}
console says:
1 tonya
2 shawn
2
read back: 0,undefined
read back: 1,undefined
so I know that
my initial values are good; i.e. they have value
Taffy sees 2 records, which is correct
It's just when I try and retrieve them, they are garbage.
What am I doing wrong?
procTech.insert({"count":1,"tech":'techName' });
procTech.insert({"count":2,"tech":'techName1' });
procTech.insert({"count":3,"tech":'techName2' });
procTech.insert({"count":3,"tech":'techName2' });
procTech.insert({"count":3,"tech":'techName2' });
procTech.insert({"count":4,"tech":'techName3' });
var query = procTech.select("count","tech"); // 3 rows
for ( var x=0; x<query.length-1; x++ ) {
console.log(query[x][0], query[x][1]);
}
I am trying to make a function in javascript that would expand/split a string with dashes and show the process ( line by line ) using recursion.
for example, the string "anna" would become:
expand("anna") = expand("an")+"---"+expand("na") ->
"a"+"---"+"n"+"---"+"n"+"---"+"a"
and the desired output would be:
anna
an---na
a---n---n---a
I have achieved doing the following so far (I know it might not be the solution I am looking):
expand("anna") = an+"---"+expand("na")
= an+"---"+n+"---"+expand("a");
= an+"---"+n+"---+"a"
the output I am getting is:
an---n---a
I can't seem to concatenate the head though to do the first example.
My javascript function of expand is as follows:
function expand(word) {
if (word.length<=1) {
return word;
} else {
mid = word.length/2;
return word.substr(0,mid) + " " + expand(word.substr(mid,word.length));
}
}
document.write(expand("anna"));
I would need some tips to do this, otherwise (if it's the wrong stackexchange forum), please guide me where to post it.
this is my crazy attempt
var Word = function(str) {
this.isSplitable = function() {
return str.length > 1;
}
this.split = function() {
var p = Math.floor(str.length / 2);
return [
new Word(str.substr(0,p)),
new Word(str.substr(p,p+1))
];
}
this.toString = function() {
return str;
}
}
var expand = function(words) {
var nwords = [];
var do_recur = false;
words.forEach(function(word){
if(word.isSplitable()) {
var splitted = word.split();
nwords.push(splitted[0]);
nwords.push(splitted[1]);
do_recur = true;
}else{
nwords.push(word);
}
});
var result = [];
nwords.forEach(function(word){
result.push( word.toString() );
});
var result = result.join("--") + "<br/>";
if(do_recur) {
return result + expand(nwords);
}else{
return "";
}
}
document.write( expand([new Word("anna")]) );
This is what you need
expand = function(word) {
return [].map.call(word, function(x) {return x+'---'}).join('')
};
The joy of functional programming.
And with added code to deal with last character:
function expand(word) {
return [].map.call(word, function(x, idx) {
if (idx < word.length - 1)
return x+'---';
else return x
}).join('')
}
As I said that it is impossible to display the "process" steps of recursion while using recursion, here is a workaround that will output your desired steps:
var levels = [];
function expand(word, level) {
if (typeof level === 'undefined') {
level = 0;
}
if (!levels[level]) {
levels[level] = [];
}
levels[level].push(word);
if (word.length <= 1) {
return word;
} else {
var mid = Math.ceil(word.length/2);
return expand(word.substr(0, mid), level+1) + '---' + expand(word.substr(mid), level+1);
}
}
expand('anna');
for (var i = 0; i < levels.length; i++) {
console.log(levels[i].join('---'));
}
to see all steps the best that I whold do is:
function expand(word) {
if (word.length<=1) {
return word;
} else {
var mid = word.length/2;
var str1 = word.substr(0,mid);
var str2 = word.substr(mid,word.length);
document.write(str1 + "---" + str2 + "<br></br>");
return expand(str1) + "---" + expand(str2);
}
}
document.write(expand("anna"));
You have to return the two parts of the string:
function expand(word) {
output="";
if (word.length<=1) {
output+=word;
return output;
} else
{
var mid = word.length/2;
output+=word.substr(0,mid)+"---"+word.substr(mid)+" \n";//this line will show the steps.
output+=expand(word.substr(0,mid))+"---"+expand(word.substr(mid,word.length-1))+" \n";
return output;
}
}
console.log(expand("anna"));
Edit:
I added the output var and in every loop I concatenate the new output to it.
It should do the trick.
Hope the problem is in your first part. According to your algorithm, you are splitting your string anna in to two parts,
an & na
so you need to expand both parts until the part length is less than or equal to one. so your required function is the below one.
function expand(word) {
if (word.length<=1) {
return word;
} else {
mid = word.length/2;
return expand(word.substr(0,mid)) + " --- " + expand(word.substr(mid,word.length));
}
}
document.write(expand("anna"));