How to execute functions in a for statement? - javascript

I've a two function currently, in the future I'll add much more and I want to execute it in a for statement.
Functions :
function load_lvl1(){
current_lvl += 1;
document.getElementById("intro").style.display = "none";
document.getElementById("level1").style.display = "block";
document.documentElement.scrollTop = 0;
document.getElementById("lvl").innerHTML = "Nivelul : " + current_lvl + " | Incercari : " + attemps;
}
function load_lvl2(){
if(attemps <= 1){
document.getElementById('error').checked = true;
document.getElementById("lvl").innerHTML = "Nivelul : " + current_lvl + " | Incercari : " + attemps;
}
How to execute all functions in a for statement like this :
for(int i = 1; i <= 3; i++){
function name[i];
}
Where i is id or number of the function, it need to look like :
function load_lvl1;
function load_lvl2;
...

You can make an array of your functions, and then iterate that array:
let func = [load_lvl1, load_lvl2];
for (let f of func) {
f(); // call it
}

Related

MVC call functions method in javascript function How come?

How can I call C# function in JavaScript?
My c# function :
#functions{
public List<string> Photo(int PostID)
{
DataBase.Current.Baglan().Open();
Objects.Current.Command.Dispose();
Objects.Current.Command.Parameters.Clear();
Objects.Current.Command.Parameters.AddWithValue("#PostID", PostID);
Objects.Current.Command.Connection = DataBase.Current.Connection;
Objects.Current.Command.CommandText = "Select * from PostPhoto where PostID=#PostID";
var ReadPhotoUrl = Objects.Current.Command.ExecuteReader();
while (ReadPhotoUrl.Read())
{
string PhotoUrl = ReadPhotoUrl["PhotoUrl"].ToString();
Posts.Current.PostPhoto.Add(PhotoUrl);
}
return Posts.Current.PostPhoto;
} }
JavaScript : `
<script type="text/javascript">
var slider_content = document.getElementById('slider');
var image = [];
var i = image.length;
function getImages(id) {
//my c# function in call ?
}
// function for next slide
function nextImage() {
if (i < image.length) {
i = i + 1;
} else {
i = 1;
}
slider_content.innerHTML = "<img src=" + image[i - 1] + ".jpg>";
}
// function for prew slide
function prewImage() {
if (i < image.length + 1 && i > 1) {
i = i - 1;
} else {
i = image.length;
}
slider_content.innerHTML = "<img src=" + image[i - 1] + ".jpg>";
}`
The intent is to call the function and pass the image to the image array.
I do not know how to ...

I get error message Uncaught ReferenceError

function printFarmInventory(monkeys, cats) {
var monkeystring = String(monkeys);
while (monkeystring.length < 3) {
monkeystring = "0" + monkeystring;
}
console.log(monkeystring + "nice");
var catstring = String(cat);
while (catstring.length < 3) {
chimpstring = "00" + catstring;
}
console.log(catstring + "great");
}
printFarmInventory(4, 7);
I'm not entirely sure I understand the context.
Changing String(cat) to String(cats) and changing chimpstring = ... to catstring = ... resolves the error and get your output as expected. Edit your question if I missed the mark.
function printFarmInventory(monkeys, cats) {
var monkeystring = String(monkeys);
while (monkeystring.length < 3) {
monkeystring = "0" + monkeystring;
}
console.log(monkeystring + "nice");
var catstring = String(cats);
while (catstring.length < 3) {
catstring = "00" + catstring;
}
console.log(catstring + "great");
}
printFarmInventory(4, 7);

How do I turn this into a callback function?

I'm new to Javascript, and callbacks are blowing my mind a little at the moment. How do I turn the teletyperDiologue function into a callback? The main reason is I want the teletyper to finish it's job before the displayOut function finishes. Thank you in advance for your help.
function displayOut() {
// images
document.getElementById("imgBox").style.backgroundImage = "url(" + db.rooms[roomLoc].roomImg + ")";
// Diologue box
diologueBox.innerHTML = ""; // Clear Box
teleTyperDiologue(db.rooms[roomLoc].description +
" The room contains: " +
(function() {
let x = "";
for (let i = 0; i < db.items.length; i++) {
if (db.items[i].location === roomLoc && db.items[i].hidden === false) {
x += db.items[i].name + ", "
}
}
x = x.slice(0, x.length -2);
if (x === "") {
x = " nothing of special interest";
}
return x;
})()
+ ".");
};
// Teletyper for Diologue Box
function teleTyperDiologue(string) {
for (let i = 0; i < string.length; i++) {
setTimeout(function() {
diologueBox.innerHTML += string.slice(i, i + 1);
}, 5 * i);
}
}
As an example:
function test(a) { a(); }
function x() { alert('hello'); }
test(x);
in your case:
function displayOut(callback) {
// images
document.getElementById("imgBox").style.backgroundImage = "url(" + db.rooms[roomLoc].roomImg + ")";
// Diologue box
diologueBox.innerHTML = ""; // Clear Box
callback(db.rooms[roomLoc].description +
" The room contains: " +
(function() {
let x = "";
for (let i = 0; i < db.items.length; i++) {
if (db.items[i].location === roomLoc && db.items[i].hidden === false) {
x += db.items[i].name + ", "
}
}
x = x.slice(0, x.length -2);
if (x === "") {
x = " nothing of special interest";
}
return x;
})()
+ ".");
};
displayOut(teleTyperDiologue);
You can pass functions around like variables and return them in functions and use them in other functions. So, when you pass a callback function as an argument to another function, you only need to pass the function definition.
See example below.
function displayOut() {
console.log("Display Out running...");
}
function teleTyperDiologue(stringParam, callback) {
console.log("Running teleTyper with string param passed of: ", stringParam);
callback();
}
teleTyperDiologue ("Test string", displayOut);

Can I do this in JavaScript? Conditional return if arguments not passed

I want to be able to pass this function either a number to return as a factorial or a number and an id for an existing element on the page, so that it can return the number as text inside my specified element. Here is my code:
function factorial(num,id){
var f=1
for (var i=2; i<=num; i++) {
f*=i;
}
if (!id) {
return f;
}
else if (id)
var msg= document.getElementById(id);
return {
msg.textContent = num + "! = " + output;
};
}
}
factorial(5,"message");
Set the element if passed then return unconditionally:
function factorial(num, id){
var f = 1;
for (var i=2; i<=num; i++) {
f *= i;
}
if (id) {
document.getElementById(id).textContent = num + "! = " + f;
}
return f;
}
alert(factorial(5));
alert(factorial(5,"message"));

JavaScript building JSON asynchronous and dynamicall

I have some trouble with asynchronous JavaScript. I call a function within a jQuery AJAX call, and in this function there are probably other asynchronous methods calls. I stuck in there on the moment.
Here I have the code snippet which is called by the jQuery AJAX function: Here I build dynamically a JSON object.
function getJSONObjektList() {
//MainJSON
var jsonObjekt = {};
jsonObjekt.ObjektId = [];
jsonObjekt.Selected = [];
doc = XYZ.GetCurrentDocument();
//probably also an asynchrounous call
doc.GetAllObjects(function (objects) {
for (var i = 0; i < objects.length; i++) {
var obj = objects[i];
var id = obj.id;
var caption = obj.caption;
var type = obj.type;
var my = obj.my;
console.log("[obj:" + obj + " id:" + id + " caption:" + caption + " type:" + type + " my: " + my + "]");
//liste alle verfuegbaren Objekte auf
jsonObjekt.ObjektId.push(id);
if (type === "Statusbox") {
doc.GetObject(id, function () {
var statusboxInhalt = this.Data.Rows;
//inner JSON object
var utilJSONObjekt;
for (var j = 0; j < statusboxInhalt.length; j++) {
// make sure to re-initialize so we don't update the same reference
utilJSONObjekt = {};
utilJSONObjekt.SelectedObjektId;
utilJSONObjekt.SelectedObjektWerte = [];
var inhalt = statusboxInhalt[j];
console.log("Name: " + inhalt[0].text + " Wert: " + inhalt[2].text);
utilJSONObjekt.SelectedObjektId = inhalt[0].text;
var valAr = inhalt[2].text.split(",");
for (var k = 0; k < valAr.length; k++) {
utilJSONObjekt.SelectedObjektWerte.push($.trim(valAr[k]));
}
jsonObjekt.Selected.push(utilJSONObjekt);
//**till here is the jsonObject not null or empty, there are some values in there**
}
});
}
}
});
//**but on the return statment is the jsonObjekt empty**
return jsonObjekt;
}
Have someone some tips how can I solve my problem, or how can I make JavaScript best asynchronously working.
Yeah, simply use callback pattern:
function getJSONObjektList(callback) { // <--- note callback
// asynchronous code starts here...
for (var k = 0; k < valAr.length; k++) {
utilJSONObjekt.SelectedObjektWerte.push($.trim(valAr[k]));
}
jsonObjekt.Selected.push(utilJSONObjekt);
callback(jsonObjekt);
// ...and ends here
}
and in your code you can use it like that:
getJSONObjektList(function(jsonObjekt) {
console.log(jsonObjekt);
// other code
});
EDIT Here's an example of two solutions to the same problem. One with callback pattern and one without it:
no callback
var add = function(x,y) {
return x+y;
};
var x = 1;
var sum = add(x, 1);
var sum2 = add(sum, 1);
console.log(sum2);
callback
var add = function(x,y,callback) {
callback(x+y);
}
var x = 1;
add(x, 1, function(sum) {
add(sum, 1, function(sum2) {
console.log(sum2);
});
});
Obviously the callback pattern is more messy, but if you are dealing with asynchronous operations then you absolutely need it, for example:
var add = function(x, y, callback) {
// add numbers after 2 seconds
setTimeout(function() {
callback(x+y);
}, 2000);
}
add(1, 2, function(sum) {
console.log(sum);
// will produce 3 after 2 seconds
// you can continue your code here
});
The idea is to pass a function which will be called after the asynchronous operation is done.

Categories