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.
Related
I'm currently working a summer course in programming to learn more while school is on summer break. In one of the assignements, I need to use the given variables to calculate the power of two values. I dont know the values beforehand, as the website generates different values when I try to run the program. I've hit my head against the wall for the whole day so any help nudging me in the right direction is appreciated!! Example of the assignment below.
**function laskuFunktio() {
var luku = noudaArvo("luku");
var eksp = noudaArvo("eksponentti");
console.log("Luku " + luku + " potenssiin " + eksp + " on:");
console.log(laskePotenssi(luku, eksp));
}**
function noudaArvo() {
luku = document.getElementById("luku").value
eksp = document.getElementById("eksponentti").value;
return ???
}
function laskePotenssi() {
if (eksp === 0) {
tulos = 1;
}
var tulos = Math.pow(luku, eksp);
return tulos
}
The first function is predetermined so I cant edit it, but the assignments are made possible without editing it or accessing the HTML files. The return statement was just edited by me to sho where I currently am stuck. Thanks for any help once more!
Look at the way noudaArvo() is called. It accepts a single parameter and expects a return value. The parameter it's passing appears to be the ID of the element it wants the value of. So don't hardcode the IDs in getElementByID(), use a parameter (which your noudaArvo() function header is missing) Return that single value, laskuFunktio() is calling it twice to get both values.
laskePotenssi() needs to accept two parameters. Here's an example of a function with 2 parameters and using them within the function body to return the sum of them. Does this help?
function test(param1, param2){
foobar = param1 + param2;
return foobar;
}
Functions may only return one thing, but it appears you'd like noudaArvo() to return the values of both the base and exponent. This can be done by answering an array ("one thing" that can hold two values).
Your first attempt at laskePotenssi uses the variable telos before declaring it. Make that let declaration first.
This can be done with prettier, more concise code, but I've maintained as much as I could from the OP as instruction.
function noudaArvo() {
luku = document.getElementById("luku").value
eksp = document.getElementById("eksponentti").value;
return [luku, eksp];
}
function laskePotenssi(luku, eksp) {
let tulos;
if (eksp === 0) {
tulos = 1;
} else {
tulos = Math.pow(luku, eksp);
}
return tulos
}
function compute() {
let [luku, eksp] = noudaArvo();
let result = laskePotenssi(luku, eksp)
alert(`the answer is ${result}`)
}
<input id="luku" placeholder="enter base"/>
<input id="eksponentti" placeholder="enter exponent"/>
<button onclick="compute()">Compute</button>
Before you mark this question as a duplicate please understand that I'm new to JS and always feared asking a question of stackoverflow.
I dont understand why calling this function returns nothing unless I enclose the function call in a console.log.
If I enclose the function call in a console.log I get the expected output "There are 3 elements in this array", however without the console.log, I dont get anything.
var counter = function (arr) {
return 'There are ' + arr.length + ' elements in this array';
};
counter(["shaun", "sara", "jessica"])
What I want to know is how I can get the output of this function without using console,.log and the reason why it does not output anything without the console.log.
console.log() is a function used to print information to the
console. return on the other hand is a call to pass some value back
up to where the call was made.
Via - CodeCademy Forum
return terminates a function and possibly returns a value to the caller of that function (whereas) console.log() will not influence the flow of your code.
Via - Difference between console.log and return in javascript?
Check and run the following Code Snippet for a practical example of how the two works:
var x = document.getElementById("first");
var y = document.getElementById("last");
var z = document.getElementById("output");
function printName(){
z.innerText = fullName();
}
function fullName(){
console.log(x.value + " " + y.value); // this wont push the concatenated name to printName()
return x.value + " " + y.value; // this will push the concatenated name to printName()
alert("y u do dis?"); // this won't run anymore since the return statement above prevents the function from invoking anything else
}
document.getElementById("btn").addEventListener("click", printName)
<input type="text" id ="first" />
<input type="text" id ="last" />
<button id="btn">Click Me</button>
<br/>
<div id="full">Hello <span id="output"></span>!!</div>
If the return statement above is removed, the console.log() alone won't return anything to printName() except display the concatenated name in your console.
var counter = function (arr) {
return 'There are ' + arr.length + ' elements in this array';
};
let functionResult = counter(["shaun", "sara", "jessica"]);
You need to return the result to a variable.
Then you can use it as you want.
So, you are actually returning something, you just have no way to view it without console.log() if you're wanting to use the returns of this function in another function, or somewhere else, you can assign it to a variable like
const myCounter = counter(["shaun", "sara", "jessica"])
console.log(myCounter)
All return is doing is making the results of the function available to be used elsewhere. If you aren't displaying it via console.log, or some other method (putting it into an HTML element or something) then you'll never "see" it anywhere, and it'll looks like the function isn't doing anything, even though it is.
How change strings in javascript arrays. I want to change array codes to strings.
How change strings in javascript arrays. I want to change array codes to strings.
How to get this;
var _0x1576 = ["SayHello", "GetCount", "Message : ", "You are welcome."];
function NewObject(_0x7aa7x2) {
var _0x7aa7x3 = 0;
this.SayHello = function (_0x7aa7x4) {
_0x7aa7x3++;
alert(_0x7aa7x2 + _0x7aa7x4);
};
this.GetCount = function () {
return _0x7aa7x3
};
}
var obj = new NewObject("Message : ");
obj.SayHello("You are welcome.");
from;
var _0x1576 = ["SayHello", "GetCount", "Message : ", "You are welcome."];
function NewObject(_0x7aa7x2) {
var _0x7aa7x3 = 0;
this[_0x1576[0]] = function (_0x7aa7x4) {
_0x7aa7x3++;
alert(_0x7aa7x2 + _0x7aa7x4);
};
this[_0x1576[1]] = function () {
return _0x7aa7x3
};
}
var obj = new NewObject(_0x1576[2]);
obj.SayHello(_0x1576[3]);
EDIT: So you have some code, where all the variable names have been replaced by numbers or indices into this global array of names, and you would like to be able to read it. There is already an answer to this question, which contains links to a bunch of useful deobfuscation tools.
Your case here looks fairly trivial - it appears that you could just do a string search and replace, substituting in the array value every time it is indexed. The regexp /_0x1576\[(\d+)\]/g should find everything that accesses the variable _0x1576 with an integer index. The inner group (\d+) should give you the index with which it was found. You could use something like this to do deobfuscate your source. However, some of the names have been lost in the obfuscation process; i.e. the name of the parameter 0x7aa7x4 in the SayHello function can't be restored. You will have to read the method, understand what its' purpose is, and try to come up with a meaningful name yourself.
One question though - just how much code do you have like this? If there are only a few names in the array of strings, then #Nina Scholz's suggestion seems fairly reasonable. Just go through them one by one, in a text editor, and use the 'Find and Replace' functionality.
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 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());