Insert a function into javascript object - javascript

I tried to insert a function into javascript object but I get
undefined
This is supposed to return a message into div.
I would like to do it the first way, but here is the both way I tried :
var errorMessage = {
empty: function(message){"<div class='field'><div class='csv'><span class='icon'></span><label class='manual' id='error-message'>" + message + "</label></div></div>"
}
};
console.log(errorMessage.empty("Hello"));
I also try this way
function errorMessage(message){
"<div class='field'><div class='csv'><span class='icon'></span><label class='manual' id='error-message'>" + message + "</label></div></div>"
}
console.log(errorMessage("hello"))

You need a return of the value literally.
The return statement ends function execution and specifies a value to be returned to the function caller.
var errorMessage = {
empty: function (message) {
return "<div class='field'><div class='csv'><span class='icon'></span><label class='manual' id='error-message'>" + message + "</label></div></div>";
}
};
console.log(errorMessage.empty("Hello"));

Your function needs to return the value
var errorMessage = {
empty: function(message){
return "<div class='field'><div class='csv'><span class='icon'></span><label class='manual' id='error-message'>" + message + "</label></div></div>";
}
};
console.log(errorMessage.empty("Hello"));

Related

Uncaught TypeError: Cannot read property '0' of undefined beqause it is unexistant

what is the best way to say devenitions=true? i cant figgure it out...
if (!defenitieGetoond) {
getDef();
defenitieGetoond = true;
} else {
getWoord();
defenitieGetoond = false;
}
This is my loop who expects that there is always a defenition? but in my json file this is not always the case. it searches to the Json file as follows.
function getDef() {
document.getElementById("demo_").innerHTML = "<br>" + savedWord[1].definitions[0].definition
// + "<br>" + "</br>"+ savedWord[1].definitions[1].definition
;
}
it needs to skip of ignore the Deffenitions[0] som how
You should need to add check in case of element exist or not. like this -
function getDef(){
const ele = document.getElementById("demo_");
if (savedWord[1].definitions && savedWord[1].definitions.length) {
ele.innerHTML = "<br>" + savedWord[1].definitions[0].definition
// + "<br>" + "</br>"+ savedWord[1].definitions[1].definition;
}
}

Unable to return value from node js module

exports.getDefiniton = function (text) {
var definition = "";
wn.definitions(text, {
useCanonical: true
, includeRelated: true
, limit: 3
}, function (e, defs) {
definition = defs[0].word + ': 1.' + defs[0].text;
definition += '\n2.' + defs[1].text;
definition += '\n3.' + defs[2].text;
console.log(definition)
});
return definition;
};
Console.log inside function(e, defs) works.
but the return statement doesn't seem to return the value.
How to properly return 'definition' variable?
since wn.definition is an Asynchronous call you should use promise or async/await or callback features.
Using callback your code would be like something like this (for example lets say you store this in a def.js file):
exports.getDefiniton = function (text, callback) {
var definition = "";
wn.definitions(text, {
useCanonical: true
, includeRelated: true
, limit: 3
}, function (e, defs) {
definition = defs[0].word + ': 1.' + defs[0].text;
definition += '\n2.' + defs[1].text;
definition += '\n3.' + defs[2].text;
console.log(definition);
callback(definition);
});
};
and you can use def.js module like this:
var defModule = require("./def");
defModule.getDefiniton("Hello", function (defintion) {
console.log(defintion);
});
UPDATE:
#Xuva in that case check the code below:
var defModule = require("./def");
defModule.getDefiniton("Hello", function (definition) {
displayMessage(text, definition);
//rest of the code ...
});

variable is not getting defined even though the code works somwhere else

so i am building a game in three js and trying to make it multiplayer throught socket.io so i am loading all of my characters into an array called players on my server side
and then i pass it to each client when they connect like so
socket.on('addPlayer', function(username) {
players.push(username)
console.log(username + " joined")
console.log("online Users " + players)
socket.broadcast.emit('syncPlayers', players)
socket.emit('syncPlayers', players)
})
and on my client syncPlayers looks like this
socket.on('syncPlayers', function(players) {
players.forEach(function(value) {
if (value == username) {
console.log("not adding " + value + " thats you ")
loadPlayerdata(username)
} else {
console.log("player Online " + value);
newplayer = value;
loadPlayerdata(newplayer)
addPlayer(newplayer)
}
});
})
then it calls this wich sends the server data
function loadPlayerdata(playerName) {
console.log(playerName)
console.log("phase1")
socket.emit('loadPlayerdata', playerName)
}
then this is called and it retrieved the player name and the data of the players location this is were my problem lies
socket.on('loadPlayerdata', function(data, username) {
toMove = threeObjects[username + "Char"]
if (data == "null" || "") {
console.log(username + " is new")
} else {
console.log(username + " Exists")
console.log(toMove)
toMove.position.set(world.spawnPointx, world.spawnPointy, world.spawnPointz)
}
i keep getting Uncaught TypeError: Cannot read property 'position' of undefined
even though i can use this
function addPlayer(playerName) {
var charObjectName = playerName + "Char"
var threeObject = models.tent1.mesh.clone();
scene.add(threeObject)
//threeObject.position.set(world.spawnPointx, world.spawnPointy, world.spawnPointz)
// set reference
threeObjects[charObjectName] = threeObject;
}
btw i have an object
var threeObjects = {};
can someone please explain why it wont work and how to fix it
You can read this answer to understand the difference between dot and brackets notation.
You are getting error because, tomove seems to be undefined and dot notation will throw error if any new user joins and if the object is empty.
Check if this helps. This will assign the object key as username and position as an value which will be array like this,
{"usernamechar": {"position": [x,y,z]}}
socket.on('loadPlayerdata', function(data, username) {
if (data == "null" || "") {
console.log(username + " is new")
} else {
console.log(username + " Exists")
threeObjects[username + "Char"]["position"] = [world.spawnPointx, world.spawnPointy, world.spawnPointz]
}
}

JavaScript global boolean Variable convert itself to string

first I'm new to Javascript, so please don't hate me if I ask such an trivial question.
I've searched some hours on Google, but I cannot find a solution for my Problem. I have declared a global Variable "status", which is false. But if I check the datatype within a function, it says "string", which is allways true, so that my Script doens't work at all.
var status = false;
function slide(element) {
if (status) {
slideUp(element);
} else {
slideDown(element);
}
}
function slideDown(element) {
status = true;
// Testprint todo remove
alert('Status is ' + status + ' and is type: ' + typeof status);
// todo
}
function slideUp(element) {
status = false;
// Testprint todo remove
alert('Status is ' + status + ' and is type: ' + typeof status);
// todo
}
Am I wrong or have I write myself a function to convert every time a boolean var to a "real" boolean var? I have tested it by myself and this show me boolean datatype...
This works fine...
var test = false;
myTestFunc();
myTestFunc() {
if(!test) {
test = true;
alert('Test is false');
} else {
test = false;
alert('Test is true');
}
alert('Test contains: ' + test + ' and has the type: ' + typeof test);
}
I see, that Javascript seems to randomly declare Variables. Is there a solution to make my Variable to a boolean datatype?
Better is there a chance to force the initialation to boolean like int varname?
The problem is window.status - see https://developer.mozilla.org/en-US/docs/Web/API/Window/status
change the name (or scope) of the var and it's all sweet
For boolen use this way from MDN doc
var test = new Boolean(false);

javascript post not doing function but load url

I am creating Stratego.
(the error is farther down)
so i am creating the map when the page is loadet whit:
turn = true;
komboType = "2kombo";
GameOpsetning = [];
GameOpsetningEnemy = [];
$(document).ready(function() {
createmap();
}
and then i do some console log to make sure it works..
function createmap () {
if (!GameStarted) {
console.log("GameOpsetning" + GameOpsetning);
if(GetSetup(Gameid)){
console.log("GameOpsetning1" + GameOpsetning);
}
else
{
console.log("GetSetup : error");
}
and here the error comes, it will open the file "game.php" whit no error. but it will not do eny thing in side the post/funcion. It will not do the alert or the if or console.log?
function GetSetup (Gameid) {
console.log("GameOpsetning3: " + GameOpsetning);
if ($.post("game.php", { gameid: Gameid }, function(data) {
alert(data);
var data2 = JSON.stringify(data);
alert(data2);
//var json = $.parseJSON(data);
if (data2.status2 && data2.status2 != "false") {
console.log("data.game: " + JSON.stringify(data.game));
GameOpsetning = JSON.stringify(data.game);
GameOpsetningEnemy = JSON.stringify(data.enemygame);
komboType = data.type;
turn = data.turn;
console.log("GameOpsetning5: " + GameOpsetning);
return true;
}
else
{
console.log("error: ");
return false;
}
})){
console.log("post: done");
}else{
console.log("post: error");
}
console.log("GameOpsetning4: " + GameOpsetning);
}
the console output:
GameOpsetning
GameOpsetning3:
post: done
GameOpsetning4:
GetSetup : error
there is no console errors and the page is return JSON
and it have try ed to do like:
console.log("GameOpsetning" + GameOpsetning);
GetSetup(Gameid);
console.log("GameOpsetning1" + GameOpsetning);
if (CheckGame()) {
then the console log is:
GameOpsetning
GameOpsetning1
GameOpsetning3:
post: done
GameOpsetning4:
GetSetup : error
Sorry for my bad English.
You're testing if($.post("game.php",... What is the result of this if test? Always true. Because anything that is not false, 0 or undefined is true. You're not testing the result of an ajax call, you're testing an ajax call (a function).
Same with if(GetSetup(Gameid)). GetSetup(Gameid) returns : console.log("GameOpsetning4: " + GameOpsetning). if(GetSetup(Gameid)) result is undefined, which explains the GetSetup : error output.
Type this in your console : if(console.log('test')) alert("yay") : it won't alert "yay", it will just log 'test' and return undefined. This is your if(GetSetup(Gameid)).
Same way, if you type if($.post("game.php")) alert('yay'), it will alert yay, because the test is always true, whatever the result of the $.post.

Categories

Resources