I want to know if it's possible to do something like this:
var myObject = {
first: "Hello" + otherObject.second() + someVariable;
}
Then call it and display in html:
html += myObject.first() or myObject.first
I want it to display all values of "someVariable" and "otherObject.second()". Currently it display something like:
function () {
return 2 * 2
}
but I want it to display "4" as a string/number so the result would be something like "Hello4". I hope you understand my question :) If thats not possible or it's a bad idea overall to do that, then let me know too and I will figure out something else.
Other people are right - you shouldn't use eval function. Especially, if it is possible to solve the problem without it.
In your case, you can replace this variable with a function, and call it when needed:
var myObject = {
first: function() {
return "Hello" + otherObject.second() + someVariable;
}
}
Now, you can call it as a function:
alert(myObject.first());
// or
html += myObject.first();
otherObject.second() and someVariable will be calculated on function call.
You can use:
console.log("foobar", myfn());
Related
I need a way where I can change the variable of a jave script function on the outcome of a different function which gets executed on a input click.
Example of the input:
<input type="image" value="74" onclick="WeaponType(this);GetDamage(74);return false;" class="CompactPistol" src=".\Weapons\Bornheim_No_3_Extended.png" alt="Bornheim No.3 Extended">
<span style="color:whitesmoke">Bornheim No. 3 Extended</span>
(I could also change the 'GetDamage' function input to 'this' instead of the value directly and then just change the function output to use the attribute 'value'. In my case it doesn't really matter as the value of one picture is set.)
My script that needs the variable currently looks like this:
<script id="ResultDamage">
function GetDamage(x) {
document.getElementById("DamageDealt").innerHTML = x;
}
</script>
This ofc only outputs the value of the function. But the value needs to be used in a more complicated calculation
What I f.e. also already tried was this:
<script id="ResultDamage">
function GetDamage(x) {
var z
z = x;
return z;
}
var d = z;
document.getElementById("DamageDealt").innerHTML = d;
</script>
and this:
<script id="ResultDamage">
function GetDamage(x) {
return x;
}
var d = GetDamage();
document.getElementById("DamageDealt").innerHTML = d;
</script>
Which gives me 'undefined'
Any help is appreciated.
As I am quite new to this keeping it simple would probably the best (if there is a simple solution)
Based on comments on the question above...
If you just need to store a value globally on the page then you can declare a variable outside of the function and set its value within any function. For example:
var a = 0;
var b = 0;
// etc.
function GetDamage(x) {
a = x;
// perform a calculation as needed
// write a result to the page as needed
}
In this case the values of a and b are stored at the page level and available to other functions, persist their values between function calls, etc. So you can have separate functions that also use those values for their own calculations.
Hi guys very new to JS and i've been working on this simple thing for too long trying to understand JS basics. Please help me out;
I have an empty H1 element that I want to fill with content using JavaScript.
I want the H1 header to contain a name from the array and display the "Hello" message.
What I want is something like:
innerHTML = greet(names[0]) for the H1 header. Im missing something trivial in understand how this is working any help would be appreciated.
names = ["Jan", "Klaas", "Piet"];
name = namen;
function greet(name){
console.log("Hallo " + name.toLowerCase());
}
document.querySelector('h1').innerHTML = greet(names[0]);
document.querySelector('h1').innerHTML = greet(names[0]); returns as "Undefined" in the H1 Element
As of now you are not returning anything from you method thus getting undefined,
You need to return value from the method.
function greet(name){
return "Hallo " + name.toLowerCase();
}
The function should return the string.
function greet(name){
return "Hallo " + name.toLowerCase();
}
There are a few things to sort out here. You dont appear to be using the namen variable so remove the second line.
You could also declare the variable names when assigning it a value.
The greet function needs to return a value rather than log to console.
var names = ["Jan", "Klaas", "Piet"];
function greet(name){
return "Hallo " + name.toLowerCase();
}
document.querySelector('h1').innerHTML = greet(names[0]);
see the codepen here
You need to return the string, like this:
names = ["Jan", "Klaas", "Piet"];
function greet(name){
return ("Hallo " + name.toLowerCase());
}
document.querySelector('h1').innerHTML = greet(names[0]);
console.log() logs the string in the browser console in the Developer Tools (shown by pressing F12). You need to return the value to assign it to the innerHTML, like i've shown above.
You also don't need to do the assignment name = namen, because name is just an alias for the value names[0] that you're passing into the function greet(). If you're doing this for use elsewhere then you'd be better off using a different variable name than name because otherwise this will cause confusion later on and potential conflicts.
You don't need "name=namen".
You have to return some values from function.
Perhaps a slightly dim question but I'm trying to design something where I'm using javascript / jquery to change the layout of a website and I'd like to see the values of both a variable name and it's current value in another div.
I was just doing $test.append('example string' + exampleVar) a lot so I thought I would make a function called test().
So far I have:
function test (test) {
$test = $('.test');
$test.append(test+"<br>");
}
and then would pass it a variable name as an argument but I can't find any way of making it display the name as a string. I know about making it as an object to access the key and value but that doesn't really seem to work here?
Bit of a long-winded way to do it, but here's an example using an object:
function tester(options) {
var keys = Object.keys(options);
console.log(keys[0] + ': ' + options[keys[0]]); // test: My value
}
tester({ test: 'My value' });
DEMO
You could use a feature of javascript where obj["prop"] is the same as obj.prop
So instead of passing the variable as a variable and hoping to get its name, you use the name as a string to get the variable's value.
If you aren't using namespaces/variables and want to a global/root variable, pass window, eg:
function test(obj, val) {
console.log(val + ": " + obj[val]);
}
var val1 = 1;
var val2 = 2;
test(window, "val1");
test(window, "val2");
(obviously you don't get the name of 'obj' - but maybe it's a start)
if you only have root/global variables (as in the example provided in the question) then you could remove obj:
function test(val) {
console.log(val + ": " + window[val]);
}
var val1 = 1;
var val2 = 2;
test("val1");
test("val2");
It seems what you want to do something like this:
var argumentName = /([^\s,]+)/g;
// fu is a function
// fu.toString look like: function myFunction (param[, param]*) { code }
function getParamNames(fu) {
var f = fu.toString();
return f.slice(f.indexOf('(')+1,f.indexOf(')')).match(argumentName);
}
Then you might want to create an helper which will take every functions:
// I choosed the console as an output, but you can set anything
function displayParameters(fu) {
var _params = getParamNames(fu);
if(_params!==null) {
for(var i=0;i<_params.length; i++) {
console.log(_params[i]);
}
} else { console.log('no parameters'); }
}
And, you will need to call: displayParameters(test);
In a function you will be using a parameter. So in that case the "variable name" will always be the name of the parameter. In this case getting the string value will always be test. I would assume this is not what you want. You were correct that the best way to do this is to use an object and iterate over the key, values. You would do this like:
var test = {
"test" : "value"
};
function test (test) {
var k, $test = $('.test');
for(k in test){
$test.append(k + "<br>");
}
}
Also, I do not think there is a way to get the variable string name. So the above would be the way to get the name of a variable.
I have an object like this:
var statistics = {
won: 0,
tie: 0,
lost: 0
};
I have a function that adds 1 to won:
var plus1 = function() {
return statistics.won++;
}
I call that function within an if/else statement like this:
plus1();
But it doesn't work. Does anyone have an idea?
It's probably that x++ returns x instead of x+1.
You are looking for
var plus1 = function() {
return ++statistics.won;
}
Looking at your code I don't really see any reason why you would return your result.
I would rewrite the function to simply be
function plus1() {
statistics.won++;
}
When it comes to having it update, I can't see any were in your code where you actually update the html. After you've run plus1(). If I run console.log(statistics) in my Console I can see that statistic.won goes up whenever I win.
As already mentioned in the comment above, if you run wins() after you've run plus1() it will all work.
This is due to to way pre/post incrementation works in JavaScript:
var one = 1;
var two = 1;
// increment `one` FIRST and THEN assign it to `three`.
var three = ++one;
// assign `two` to `four`, THEN increment it
var four = two++;
So in your code, you're assigning the value of statistics.won to the return value first and then incrementing it. You can see the difference in how they work here.
So, as I mentioned in the comments, return ++statistics.won; is the solution you need.
I've got a function that wants to access a global variable, the name of which arrives as a string argument. This is how it looks now, using eval:
function echoVar(whichone){
document.write(eval(whichone));
}
I thought I'd just use the window[] syntax and have this:
function echoVar(whichone) {
document.write(window[whichone]);
}
If I create a var and call it like this, it doc writes ABC as expected:
var abc = "ABC";
echoVar("abc");
If the var I want to access is an array element though, it doesn't work:
var def = ["DEF"];
echoVar("def[0]"); //fails with undefined
Obviously that's actually executing window[def[0]] which rightly gives undefined (because there's no variable called DEF). What I actually want to happen is that it executes window["def"][0].
The only way I know to achieve this, is to do a split on the whichone parameter with "[" as the delimiter and then use the split [0] as the window index and a parseInt on split [1] to get the index, like this:
function echoVar(whichone){
if(whichone.indexOf("[")==-1){
document.write(window[whichone]);
}
else{
var s = whichone.split("[");
var nam = s[0];
var idx = parseInt(s[1]);
document.write( window[nam][idx] );
}
}
Am I overlooking something obvious? I'd rather keep the eval than have to do all that.
If you dislike using eval in your code, you can always do this:
function echoVar(whichone) {
document.write(Function("return " + whichone)());
}
Unless this is some sick experiment, you should never be writing Javascript code that looks like this. This is terrible; you need to re-think your design. I know this isn't what you're looking for, but it's the right answer.
The fact is you've got a piece of a javscript expression in a string so you either have to parse it yourself or use eval to parse it for you unless you change the way it's passed like this:
function echoVar(a,b) {
var x = window[a];
if (b) {
x = x[b];
}
document.write(x);
}
And, then you can pass it differently like this:
var def = ["DEF"];
echoVar("def", 0); // def[0]
You could even make this support multiple dimensions if you needed to.
function echoVar(a) {
var x = window[a];
for (var i = 1; i < arguments.length; i++) {
x = x[arguments[i]];
}
document.write(x);
}
var def = {myObject: {length: 3}}
echoVar("def", "myObject", "length"); // def["myObject"]["length"] or def.myObject.length
You can see it work here: http://jsfiddle.net/jfriend00/dANwq/
It would be simpler to lose the brackets and call the item with dot notation
function reval(s, O){
s= String(s);
O= O || window;
var N= s.split(".");
while(O && N.length) O= O[N.shift()];
return O || s;
}
window.def= ['definition'];
alert(reval('def.0'))
/* returned value: (String)
definition
*/