Supose I have a function that calls the same function twice, with differents parameter each time, some like this:
function one(){
two(a,b);
two(c,d);
}
When I call function one, only the first function two is executed, but not the second one. Is there a way to do this in Javascript only? (not Jquery)
Here's the code in cuestion (is a little text-based RPG)
window.onload = init;
function init(){
document.onmousedown = function disableselect(e) {return false;};
/*ELEMENTS*/
var monsterPicture = document.createElement('div');
monsterPicture.setAttribute('class', 'monsterPicture');
monsterPicture.style.position = 'absolute';
monsterPicture.style.top = '0';
monsterPicture.style.right = '0';
monsterPicture.style.bottom = '0';
monsterPicture.style.left = '0';
monsterPicture.style.height = '350px';
monsterPicture.style.width = '350px';
monsterPicture.style.margin = 'auto';
monsterPicture.style.backgroundColor = 'grey';
document.body.appendChild(monsterPicture);
var textInfo = document.createElement('textarea');
textInfo.setAttribute('class', 'textInfo');
textInfo.style.position = 'absolute';
textInfo.style.top = '0';
textInfo.style.bottom = '0';
textInfo.style.right = '0';
textInfo.style.height = '350px';
textInfo.style.width = '250px';
textInfo.style.margin = 'auto 50px auto auto';
textInfo.style.backgroundColor = 'white';
textInfo.style.overflowY = 'hidden';
textInfo.style.resize = 'none';
textInfo.readOnly = 'true';
textInfo.disabled = 'true';
textInfo.style.cursor = "default";
document.body.appendChild(textInfo);
var statsArea = document.createElement('div');
statsArea.setAttribute('class', 'statsArea');
statsArea.style.position = 'absolute';
statsArea.style.top = '0';
statsArea.style.top = '0';
statsArea.style.bottom = '0';
statsArea.style.right = '0';
statsArea.style.height = '350px';
statsArea.style.width = '200px';
statsArea.style.margin = 'auto 700px auto auto';
document.body.appendChild(statsArea);
var heroInfo = document.createElement('textarea');
heroInfo.setAttribute('class', 'heroInfo');
heroInfo.style.height = '160px';
heroInfo.style.width = '200px';
heroInfo.style.marginTop = '10px';
heroInfo.style.backgroundColor = 'white';
heroInfo.style.overflowY = 'hidden';
heroInfo.style.resize = 'none';
heroInfo.readOnly = 'true';
heroInfo.disabled = 'true';
heroInfo.style.cursor = "default";
document.body.appendChild(heroInfo);
var monsterInfo = document.createElement('textarea');
monsterInfo.setAttribute('class', 'monsterInfo');
monsterInfo.style.height = '160px';
monsterInfo.style.width = '200px';
monsterInfo.style.backgroundColor = 'white';
monsterInfo.style.overflowY = 'hidden';
monsterInfo.style.resize = 'none';
monsterInfo.readOnly = 'true';
monsterInfo.disabled = 'true';
monsterInfo.style.cursor = "default";
document.body.appendChild(monsterInfo);
statsArea.appendChild(monsterInfo);
statsArea.appendChild(heroInfo);
/*CONSTRUCTOR FUNCTIONS*/
function character (name, hitpoints, armorclass, attackbonus, weapondamage) {
this.name = name;
this.hitPoints = hitpoints;
this.armorClass = armorclass;
this.attackBonus = attackbonus;
this.weaponDamage = weapondamage;
this.stats = function(){
return this.name + "\n" +
"Hit Points: " + this.hitPoints + "\n" +
"Armor Class: " + this.armorClass + "\n" +
"Attack Bonus: " + this.attackBonus + "\n" +
"Weapon Damage: " + this.weaponDamage;
};
this.alive = true;
this.reset = function (){
this.hitPoints = hitpoints;
this.armorClass = armorclass;
this.attackBonus = attackbonus;
this.weaponDamage = weapondamage;
};
}
var Arquer = new character("Arquer", 15, 6, 5, 8);
function selectMonster () {
var werewolf = new character("Werewolf", 15, 4, 4, 3);
var goblin = new character("Goblin", 15, 4, 4, 3);
switch(Math.floor(Math.random()*2)+1){
case 1: return werewolf;
case 2: return goblin;
}
}
var buttonAttack= document.createElement('input');
buttonAttack.setAttribute('type','button');
buttonAttack.setAttribute('value','Attack');
document.body.appendChild(buttonAttack);
var current_monster = selectMonster();
heroInfo.value = Arquer.stats() + "\n" + "Alive: " + Arquer.alive;
monsterInfo.value = current_monster.stats() + "\n" + "Alive: " + current_monster.alive;
buttonAttack.onclick = function(){
if (current_monster.hitPoints <= 0){current_monster = selectMonster();monsterInfo.value = current_monster.stats() + "\n" + "Alive: " + current_monster.alive;}
else{battle(Arquer, current_monster);}
};
function battle (hero, monster){
if(hero.alive===true && monster.alive===true){
var heroIniciative = Math.floor(Math.random()*20)+1;
var monsterIniciative = Math.floor(Math.random()*20)+1;
var attacker;
var defender;
var attackerInfo;
var defenderInfo;
/*INICIATIVE ROLL*/
if (heroIniciative >= monsterIniciative){
attacker = hero;
defender = monster;
attackerInfo = heroInfo;
defenderInfo = monsterInfo;
textInfo.value += attacker.name + " attacks first!: " + heroIniciative + " vs " + monsterIniciative + "\n";
textInfo.scrollTop = textInfo.scrollHeight;
attack(attacker, defender, attackerInfo, defenderInfo);
attack(defender, attacker, defenderInfo, attackerInfo);
}
else {
attacker = monster;
defender = hero;
attackerInfo = monsterInfo;
defenderInfo = heroInfo;
textInfo.value += attacker.name + " attacks first!: " + monsterIniciative + " vs " + heroIniciative + "\n",
textInfo.scrollTop = textInfo.scrollHeight;
attack(attacker, defender, attackerInfo, defenderInfo);
attack(defender, attacker, defenderInfo, attackerInfo);
}
check_defeat(attacker, defender, attackerInfo, defenderInfo);
}
else {reset (hero, monster);
}
}
function attack (attacker, defender, attackerInfo, defenderInfo){
var d20 = Math.floor(Math.random()*20)+1;
var d_wp = Math.floor(Math.random()*attacker.weaponDamage)+1;
/*ROUND ONE*/
if (d20+attacker.attackBonus>defender.armorClass){
textInfo.value += attacker.name +" d20+" + attacker.attackBonus+": " + (d20+attacker.attackBonus)+ " vs AC " + defender.armorClass + "\n" + attacker.name +" hits! d" + attacker.weaponDamage + ": " + d_wp + "\n";
textInfo.scrollTop = textInfo.scrollHeight;
defender.hitPoints = defender.hitPoints - d_wp;
defenderInfo.value = defender.stats();
defenderInfo.append("\n" + "Alive: " + defender.alive);
}
else {
textInfo.value += attacker.name + " misses! d20+" + attacker.attackBonus+": " + (d20+attacker.attackBonus)+ " vs AC " + defender.armorClass;
textInfo.scrollTop = textInfo.scrollHeight;
defenderInfo.value = defender.stats();
defenderInfo.append("\n" + "Alive: " + defender.alive);
}}
function check_defeat (attacker, defender, attackerInfo, defenderInfo) {
if (attacker.hitPoints <= 0){
attacker.hitPoints = 0;
attacker.alive = false,
attackerInfo.value = attacker.stats();
attackerInfo.append("\n" + "Alive: " + attacker.alive);
textInfo.value += "\n" +defender.name + " killed " + attacker.name + "!";
textInfo.scrollTop = textInfo.scrollHeight;
}
if (defender.hitPoints <= 0){
defender.hitPoints = 0;
defender.alive = false,
defenderInfo.value = defender.stats();
defenderInfo.append("\n" + "Alive: " + defender.alive);
textInfo.value += "\n" + attacker.name + " killed " + defender.name + "!";
}
}
function reset (hero, monster) {
if (hero.alive===false){
hero.reset();
hero.alive = true;
heroInfo.value = hero.stats();
heroInfo.append("\n" + "Alive: " + hero.alive);
}
if (monster.alive===false){
monster.reset();
monster.alive = true;
monsterInfo.value = monster.stats();
monsterInfo.append("\n" + "Alive: " + monster.alive);
}
}
}
(For some reason it doesn't work in jsfiddle). The problem is in the function battle.
function battle (hero, monster){
if(hero.alive===true && monster.alive===true){
var heroIniciative = Math.floor(Math.random()*20)+1;
var monsterIniciative = Math.floor(Math.random()*20)+1;
var attacker;
var defender;
var attackerInfo;
var defenderInfo;
/*INICIATIVE ROLL*/
if (heroIniciative >= monsterIniciative){
attacker = hero;
defender = monster;
attackerInfo = heroInfo;
defenderInfo = monsterInfo;
textInfo.value += attacker.name + " attacks first!: " + heroIniciative + " vs " + monsterIniciative + "\n";
textInfo.scrollTop = textInfo.scrollHeight;
attack(attacker, defender, attackerInfo, defenderInfo);
attack(defender, attacker, defenderInfo, attackerInfo);
}
else {
attacker = monster;
defender = hero;
attackerInfo = monsterInfo;
defenderInfo = heroInfo;
textInfo.value += attacker.name + " attacks first!: " + monsterIniciative + " vs " + heroIniciative + "\n",
textInfo.scrollTop = textInfo.scrollHeight;
attack(attacker, defender, attackerInfo, defenderInfo);
attack(defender, attacker, defenderInfo, attackerInfo);
}
check_defeat(attacker, defender, attackerInfo, defenderInfo);
}
else {reset (hero, monster);
}
}
When I call it, it just execute the first function attack, but not the second one.
buttonAttack.onclick = function(){
if (current_monster.hitPoints <= 0){current_monster = selectMonster();monsterInfo.value = current_monster.stats() + "\n" + "Alive: " + current_monster.alive;}
else{battle(Arquer, current_monster);}
};
When executing a function you don't have to write function up front.
try
function one(){
two(a,b);
two(c,d);
}
It should work -
function two(a,b){
console.log(a+b);
}
function one(){
two(1,2);
two(3,4);
}
one();
output:
2
7
the first function two is executed
This is highly unlikely; why do you believe it was executed? Before you call anything, or anything is executed, there is a syntax error, probably something like "Unexpected token ;", because the syntax
function two(a, b);
is invalid; function definitions must have a body in curly braces. You would see the error if you looked at the console; did you? It must be:
function two(a, b) { }
But apparently you just want to call the function, in which case you should use the basic function call syntax of two(a, b). function is for defining functions, not calling them.
Best and easiest solution is to use Promist.all() with nodejs
Example
let _ = require('underscore')
let response = ['some data','other data']
return Promise.all(_.map(response, function (data) { return
functionName(data) }))
.then((response)=>{
console.log(response)
})
Result
['response1','response2']
you can simply call a function twice or any time you want just remember its arguments and its data types since you are not forced to put data type on function call but if there is wrong data type it can create serious mess.
//currently in a mess
I created a list of buttons from code behind, and append them on some div, how ever each button has an onclick java script function
here is how I did it:
string[] messages = CM.GetMessages(Session["USER_EMAIL"].ToString()).Split(new string[] { "$STARTCHAT$" }, StringSplitOptions.None);
string[] usersalone = CM.GetChaters(Session["USER_EMAIL"].ToString()).Split(new string[] { "$NEWUSER$" }, StringSplitOptions.None);
string[] username = CM.GetUserNames(Session["USER_EMAIL"].ToString()).Split(new string[] { "$NEWUSER$" }, StringSplitOptions.None);
for (int i = messages.Length-2; i>=0; i--)
{
Button b = new Button();
b.ID = Session["USER_EMAIL"].ToString()+username[i];
b.Text = "Chat With: " + usersalone[i] ;
b.Width = 250;
b.Height = 100;
b.OnClientClick = "return DisplayMessage('" + messages[i+1] + "','" + username[i] + "','" + Session["USER_EMAIL"].ToString() + "')";
b.Style.Add("background-color", "rgb(246, 246, 246)");
// lblChatwith.Text = username[i];
NewMsgNotArrow.Controls.Add(b);
}
and here is my java script function:
function DisplayMessage(messages, from, username) {
document.getElementById("AllMessages").innerText ="";
document.getElementById("DivDisplayMessage").style.visibility = "visible";
document.getElementById("lblChatwith").innerText = from;
var MessageForEachUser = messages.split("$SAMECHATNEWTEXT$");
for (var i = 0; i < MessageForEachUser.length; i++)
{
var ck = MessageForEachUser[i].indexOf("$" + from.toUpperCase() + "$") > -1;
if (ck == true) {
document.getElementById("AllMessages").innerText += from.toUpperCase() + ":\n";
var temp = MessageForEachUser[i].split("$" + from.toUpperCase() + "$");
MessageForEachUser[i] = temp[0];
}
if (ck == false) {
document.getElementById("AllMessages").innerText += username.toUpperCase() + ":\n";
var temp = MessageForEachUser[i].split("$" + username.toUpperCase() + "$");
MessageForEachUser[i] = temp[0];
}
document.getElementById("AllMessages").innerText += MessageForEachUser[i] + "\n______________________________________________________" + "\n";
}
return false;
}
every thing is working well but, when i want to use one of the labels like "lblchatwith" from code behind it return an empty string.
var fillets = {};
function fillet_change(thumb, cid, sku, width, selected_matte)
{
switch(selected_matte)
{
case "fillet_matte_layer_bottom":
moulding_matte_canvas_width[i] = $("#opening_" + i).width();
moulding_matte_canvas_height[i] = $("#opening_" + i).height();
index = 2;
break;
case "fillet_matte_layer_middle":
moulding_matte_canvas_width[i] = $("#opening_" + i).width() + 10;
moulding_matte_canvas_height[i] = $("#opening_" + i).height() + 10;
index = 1;
break;
case "fillet_matte_layer_top":
if (mattes_default_selected == true)
{
moulding_matte_canvas_width[i] = $("#opening_" + i).width() + 22;
moulding_matte_canvas_height[i] = $("#opening_" + i).height() + 22;
}
else
{
moulding_matte_canvas_width[i] = $("#opening_" + i).width();
moulding_matte_canvas_height[i] = $("#opening_" + i).height();
}
index = 0;
break;
}
var fillet = {
index: index,
imgsrc: thumb,
width: width,
cid: cid,
sku: sku
};
fillets[index] = fillet;
}
However I am getting an error : Uncaught TypeError: Cannot set property '2' of undefined
So my question is how can I add the fillet object to another object or an array (doesn’t matter)?
Approach for adding as if you add in a queue.
var fruits = [{size: 3, color: 'yellow'}, {size: 5, color: 'green'}];
fruits.push({size:9, color: 'black'});
console.dir(fruits);
It must be Array[3].
0: Object
color: "yellow"
size: 3
proto: Object
1: Object
color: "green"
size: 5
proto: Object
2: Object
color: "black"
size: 9
proto: Object
Try adding a index variable
function fillet_change(thumb, cid, sku, width, selected_matte)
{
var index;
switch(selected_matte)
"Cannot set property '2' of undefined" means that you call variable[2] = 'something'; and variable is undefined.
This may happen in that strings:
moulding_matte_canvas_width[i] = $("#opening_" + i).width();
moulding_matte_canvas_height[i] = $("#opening_" + i).height();
In your code I can't see where you define moulding_matte_canvas_width, moulding_matte_canvas_height variables. Are you sure that this variabels are defined and length of this array >= 3?
It turns out I had fillets defined somewhere else. So I changed the name of the variable and it works:
var fillet_array = [];
function fillet_change(thumb, cid, sku, width, selected_matte)
{
if (typeof(selected_matte) === "undefined")
{
selected_matte = fillet_selected_matte;
//console.log("fillet_selected_matte: "+ fillet_selected_matte);
}
if (typeof(width) === "undefined")
{
width = .31;
}
if (mattes_selected_type == 15) //letter mattes
{
alert("Fillets can only be applied to rectangular openings. Your current layout does not contain any rectangular openings, fillet was not applied");
return;
}
var img = new Image();
img.src = SITE_URL + '/system/components/compimg/' + thumb + '/pattern';
img.onload = function()
{
img.width = width * ppi;
img.height = width * ppi;
$( document ).ready(function()
{
$("div[id^='opening_']").each(function(i) //for each div that has an id of opening_(number)
{
//Set the values in the array with the width and height
switch(selected_matte)
{
case "fillet_matte_layer_bottom":
moulding_matte_canvas_width[i] = $("#opening_" + i).width();
moulding_matte_canvas_height[i] = $("#opening_" + i).height();
index = 2;
break;
case "fillet_matte_layer_middle":
moulding_matte_canvas_width[i] = $("#opening_" + i).width() + 10;
moulding_matte_canvas_height[i] = $("#opening_" + i).height() + 10;
index = 1;
break;
case "fillet_matte_layer_top":
if (mattes_default_selected == true)
{
moulding_matte_canvas_width[i] = $("#opening_" + i).width() + 22;
moulding_matte_canvas_height[i] = $("#opening_" + i).height() + 22;
}
else
{
moulding_matte_canvas_width[i] = $("#opening_" + i).width();
moulding_matte_canvas_height[i] = $("#opening_" + i).height();
}
index = 0;
break;
}
var fillet_xml = "<imgsrc>" + thumb + "</imgsrc><width>" + width + "</width><cid>" + cid + "</cid><sku>" + sku + "</sku>";
var fillet = {
index: index,
imgsrc: thumb,
width: width,
cid: cid,
sku: sku
};
fillet_array.push(fillet);
mattes_mattes_xml = mattes_get_mattes_xml().replace("<fillet index='" + index + "'></fillet>", "<fillet index='" + index + "'>" + fillet_xml + "</fillet>");
common_get_order_xml();
moulding_draw(img, "fillet", selected_matte); //Call the moulding_draw function, which draws the fillet on the canvas
});
});
};
}
I'm creating a text based game with Javscript and I am having some issues with referencing a JSON array.
var cRecipes = [];
function craftItem(id){
var n = cRecipes[id].name;
var t = cRecipes[id].type;
var i1 = cRecipes[id].item1;
var a1 = parseInt(cRecipes[id].amount1);
var i2 = cRecipes[id].item2;
var a2 = parseInt(cRecipes[id].amount2);
for (i = 0; i < inventory.length; i++){
if (inventory[i].item == i1 && inventory[i].amount >= a1){
var inv1 = parseInt(inventory[i].amount)
parseInt(inventory[i].amount) -= a1;
a1 = 0;
}
if (inventory[i].item == i2 && inventory[i].amount >= a2){
parseInt(inventory[i].amount) -= a2;
a2 = 0;
}
}
if (a1 == 0 && a2 == 0){
if (t == "Hat"){
cHat = products[rId].name;
command(products[rId].effect);
p(n + " crafted");
}
else {
p("Insufficient items");
}
}
}
function loadCrafting(){
cRecipes = [
{"name":"Mega Fedora", "type":"Hat", "item1": "Euphorite", "amount1":4, "item2":"Essence Of Euphoria", "amount2":2, "effect":""},
{"name":"Mega Fedora 2", "type":"Hat", "item1": "Euphorite", "amount1":4, "item2":"Essence Of Euphoria", "amount2":2, "effect":""},
];
c();
p("-- Your Crafting --");
back();
for (cr = 0; cr < cRecipes.length; cr++){
p("<span class='choice' id='c"+ cr + "'>" + cRecipes[cr].name +", " + cRecipes[cr].type + ", " + cRecipes[cr].item1 + " x" + cRecipes[cr].amount1 + ", " + cRecipes[cr].item2 + " x" + cRecipes[cr].amount2 + "</span>");
$("#c" + cr).click(function(){craftItem(cr);});
}
}
When running the script, I am given the following error.
Uncaught TypeError: Cannot read property 'name' of undefined
I have used similar methods with other parts of my game and have had no issues so this
So, i'm adding 2 characters 4 levels together (hp, attack, strength and defense) and then comparing them. However I am having a problem. when the numbers are added together they're added together as a string so it outputs as follows. 9060951/99709940 instead of 246 (90+60+95+1)/308 (99+70+99+40). Here is what I am doing.
function calculate(player1, player2) {
var total1 = player1.getTotal();
var total2 = player2.getTotal();
var differencePercentage;
if(total1 > total2) {
differencePercentage = total2 + "/" + total1 + " = " + (total2/total1);
} else {
differencePercentage = total1 + "/" + total2 + " = " + (total1/total2);
}
var percentage = differencePercentage;
return percentage;
}
function Player(hp, attack, strength, defense) {
this.hp = parseInt(hp);
this.attack = parseInt(attack);
this.strength = parseInt(strength);
this.defense = parseInt(defense);
this.getTotal = function() {
var total = 0;
total = hp + attack + strength + defense;
return total;
}
}
Why is this happening?
You are parsing the Ints into this.hp, this.attack etc. in your Player function but not into the getTotal function
Try this
this.getTotal = function() {
var total = 0;
total = this.hp + this.attack + this.strength + this.defense;
return total;
}