Javascript how return works - javascript

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/

Related

function prevents rest of code from working

function updateScreen() {
var textOutput = "";
setScreen("yellowScreen");
for (var i=0; i < finalColor.length; i++){
var newIndex = i+1;
textOutput = (((textOutput + newIndex +". NAME: " +finalName[i] + ", "
+ "scientific name is") + finalScientificName[i] + ", " + "this bird is
")+ finalConservationStatues[i] + "and they eat ")+ finalDiet[i]+"\n\n";
}
setText("yellowOutput", textOutput);
console.log(textOutput);
}
onEvent("yellowButton", "click", function( ) {
yellowFilter();
upDateScreen();
});
the function yellowFilter prevents anything else to run
function yellowFilter() {
for (var i = 0; color.length; i++) {
if (color[i] == 'Yellow' ) {
appendItem(finalColor, color[i]);
appendItem(finalDiet, diet[i]);
appendItem(finalConservationStatues, conservationStatus[i]);
appendItem(finalScientificName, scientificName[i]);
appendItem(finalName, Name[i]);
console.log(finalColor);
}
}
}
is there anything wrong with these functions the update screen function doesn't run if the yellowFilter runs but yellowFilter needs to run so that upDateScreen can run properly
Without actually going through anything I see one error immediately:
for (var i = 0; color.length; i++)
The second statement in a for loop needs to be a conditional

Why does my ng-class display even when false

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

My function is only working inside of the else in an if statement?

If you need the edit function, please let me know. Anyhow, I'm going through a JSON table and getting the ID of an item on ROBLOX. In case you don't work with ROBLOX, we'll use letters. If A's name is B's asset ID, then change A's name to B's name. That's basically what I want to do, but it's not working. Here's my if statement.
function loop(page) {
$.get("https://search.roblox.com/catalog/json?Subcategory=1&CreatorID=62277089&CurrencyType=0&pxMin=0&pxMax=0&SortType=3&SortAggregation=5&SortCurrency=0&IncludeNotForSale=true&LegendExpanded=false&Category=1&PageNumber=" + page).success(function(data) {
console.log("On page: " + page);
for (var i = 0; i < data.length; i++) {
var prevName = data[i].Name;
if (!isNaN(prevName)) {
console.log("Name was Number, changing...")
$.get("https://www.roblox.com/item.aspx?id=" + Number(prevName)).success(function(data) {
var name = $("h1.notranslate", data).text();
edit(data[i].AssetId, name);
console.log("Changed to " + name);
});
} else {
edit(data[i].AssetId, prevName);
}
}
});
}
for (var i = 1; i < 4; i++) {
loop(i);
}
Thanks for your help.
Both of your $.get functions return data into the data variable. Try this
...
if (!isNaN(prevName)) {
console.log("Name was Number, changing...")
$.get("https://www.roblox.com/item.aspx?id=" + Number(prevName)).success(function(data2) {
var name = $("h1.notranslate", data2).text();
edit(data[i].AssetId, name);
console.log("Changed to " + name);
});
} else {
edit(data[i].AssetId, prevName);
}
...

Javascript For Loop interrupted by function call?

I have a for-loop that is terminating without finishing the loop. It seems to be related to whether or not a call to another function is made within the loop.
this.cycle = function() {
var list = this.getBreaches("Uncontained");
if (list.length > 0) {
for (i=0; i < list.length; i++) {
this.saveVsRupture(DC=11, i); //calls this.rupture() if save failed
}}
return 1;
};
this.saveVsRupture() calls a function that rolls a d20 and checks the result. If the save fails, it calls a method called this.rupture() that does some adjusting to this.
Problem
If the saving throw is successful, the loop continues, but if the saving throw fails, it runs the this.rupture() function and then breaks the for-loop. It should keep running the for-loop.
Why is this happening?
Additional Details
Here are the other functions...
savingThrow = function(DC=11) {
// DC = Difficulty Check on a d20
try {
if (0 <= DC) {
var roll = Math.floor((Math.random() * 20))+1; //roll d20
var msg = "(Rolled "+roll+" vs DC "+DC+")";
console.log(msg);
if (roll >= DC) { //Saved
return true;
}
else { //Failed save
return false;
}
}
}
catch(e) {
console.log("Exception in savingThrow: "+e);
};
};
this.saveVsRupture = function(DC=1, i=null) {
try {
if (!savingThrow(DC)) {
this.rupture(i);
return false;
}
return true;
}
catch(e) {
console.log(e);
}
};
this.rupture = function(i=null) {
if (i == null) {
i = range(1,this.damageList.length).sample();
}
var hole = this.damageList[i];
var dmg = range(1,this.harmonics()).sample();
hole.rupture(dmg);
msg = "*ALERT* " + hole + " expanded by " + dmg + "% Hull Integrity #"+this.hullIntegrity();
this.log(msg);
if (hole.size % 10 == 0) {
this.health -= 25;
msg = "The ship creaks ominously.";
this.log(msg);
}
return 1;
};
The correct syntax for the for-loop declares the counter variable.
for (var i=0; i < list.length; i++) {etc..
/// Causes the For-Loop to exit prematurely...
for (i=0; i < list.length; i++) {etc..
Once the "var i=0" is used, the for-loop operates as expected.
consider implementing a try-catch in your for loop, with your saveVsRupture function within the try. This implementation will catch errors in your function but allow the program to keep running.
Change the saveVsRupture function like this:
function saveVsRupture(a,b) {
try{
//your saveVsRupture code here...
}
catch(e){}
}
Your should catch problems that occurred in your code with try,catch block to prevent throw them to top level of your code (the browser in this example) .
Don't use return in for loop!
Change your code as following:
this.cycle = function() {
var list = this.getBreaches("Uncontained");
if (list.length > 0) {
for (i=0; i < list.length; i++) {
var temp = this.saveVsRupture(DC=11, i); //calls this.rupture() if save failed
console.log(temp);
}}
return 1;
};

How to create a function in Javascript which calls other functions

I have a task that I am trying to solve. I have created a function named printRange which will print the number range between rangeStart and rangeStop and all values separated by a comma.
var rangeStart, rangeStop;
function printRange(rangeStart, rangeStop) {
var numberRow = "";
for(var i=rangeStart; i <= rangeStop; i++) {
numberRow += "," + i;
}
return numberRow;
}
I have also created another function named "printRangeReversed" which will print the range but in the opposite order. Again, the values will be separated by a comma.
function printRangeReversed(rangeStart, rangeStop) {
var numberRow = "";
for(var i=rangeStop; i >= rangeStart; i--) {
numberRow += "," + i;
}
return numberRow;
}
Now I should create a new function called printAnyRange. If 'rangeStart' is smaller than 'rangeStop' then I should call the function 'printRange()'. If 'rangeStart' is greater than 'rangeStop' then I should call the function 'printRangeReversed()'.
How do I do this? I have tried myself with the code below but does not get any satisfying results... Thanks in advance!
function printAnyRange(rangeStart, rangeStop) {
var numberRow = "";
if(rangeStart < rangeStop) {
printRange();
}
else {
printRangeReversed();
}
}
printAnyRange(24, 41);
You forgot to supply the arguments to printRange() and printRangeReversed().
Just change
if(rangeStart < rangeStop) {
printRange();
}
else {
printRangeReversed();
}
with
if(rangeStart < rangeStop) {
printRange(rangeStart, rangeStop);
}
else {
printRangeReversed(rangeStart, rangeStop);
}
and it should work.

Categories

Resources