It this javascript function possible? - javascript

When debugging I often write something like console.log("foo:"+foo+", bar:"+bar) is it possible to write a function logValues(foo,bar) which would give the same output? Essentially I'm asking if there is a way to go from a variable to that variable's name. Do I have to setting for looping for an arguments array just using the index yielding [0]: 'value of foo, [1]: 'value of bar'
Thanks for reading

Try this code:
var logValues = function(){
var args = arguments;
for(var i in args)
window.console.log(args[i] + ": " + eval(args[i]));
}
logValues("foo","bar");

(none of these options directly answer the question; but should give better alternatives for what you're trying to do)
WebKit's inspector (and I assume Firebug) allow you to log complex types, no need to write helpers at all!
Just console.log(foo, bar) and you're set. Or console.log({foo: foo, bar: bar}) if you want the variable names in the output.
Alternative Answer:
You might consider a helper that just takes an object and spits it out - it doesn't save much, if any, typing; but results in more readable code that pretty closely matches the logged output.
window.logValues = function(values) {
var k, v;
var pairs = [];
for (k in values) {
v = values[k];
pairs.push("" + k + ": " + v);
}
console.log(pairs.join(", "));
};
You then call it like:
logValues({foo: 1, bar: "asdf"})
To which you see:
foo: 1, bar: asdf
Option #3:
Or a more terse example that may strip out a little more type information than you like:
window.logValues = function(values) {
console.log(JSON.stringify(values));
}

function logValue(foo)
{
console.log(foo + ": " + eval(foo));
}
var foo = "something";
logValue("foo");
This will work, but you have to make sure that your foo variable is available inside the logValue function.

I use two arrays to store all data in:
data=[];
names=[];
foo=1;
data[1]="foovalue";
names[1]="foo";
bar=2;
data[bar]=28;
names[bar]="bar";
etcetera, all global values that I use in a project
Next you can write code like
data[foo]=data[foo] + data[bar];
data[bar]=data[bar]+22;
function log(a,b){
//something like
var=text;
text=names[a] + " = " + data[a];
text=text + linebreak + names[b] + " = " + data[b];
}
you can also use it to write to html;
function writedataval(arrnumber){
document.getElementById(names[arrnumber] ).innerHTML = data[arrnumber] ;
}
writedataval(foo);
There has to be a tag with id="foo" before you can run this code succesfully
I think this approach very beneficial in many ways as you can also use the array indexes to acces data and name .

Related

How i can do a function who can be applied to any variables at the end of the variable?

I'm trying to do a function like .split() or .replace() or .remove(), i think is like a prototype function, how i can make this example works:
this.logThis = function(a) {
console.log("The " + this + "is cool like a " + a);
}
var food = "apple";
food.logThis("orange");
To get this Output:
> "The apple is cool like a orange"
Important: I need the most short code possibly, pure javascript, NO JQUERY
If you want to be able to call the function on a string, you'll need to extend the String prototype:
String.prototype.logThis = function(a) {
console.log("The " + this + " is cool like a " + a);
}
var food = "apple";
food.logThis("orange");
This'll work, but you might want to alter it slightly to use a more modern JavaScript syntax:
String.prototype.logThis = function(a) {
console.log(`The ${this} is cool like a ${a}`);
}
const food = "apple";
food.logThis("orange")
It is also worth pointing out that extending native objects is considered by many to be a bad practice (here's why), so you might rather alter your function to avoid this.
Here's one way of doing that:
const obj = {
food: 'apple',
logThis(a) {
console.log(`The ${this.food} is cool like a ${a}`);
}
}
obj.logThis("orange");
I will preface this by saying that generally, you don't want to extend prototypes. For that I will refer you here.
However - if you really wanted to, you could:
String.prototype.logThis = function(a) {
console.log("The " + this + " is cool like a " + a);
}
var food = "apple";
food.logThis("orange");

Passing function to innerHTML method

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.

Can I access a variable's name as a string after passing it as an argument to another 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.

Best way to pass a guid from a javascript function as a value not a reference?

I have a function to generate guids for testing:
helpers.guid = function(){
var guid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
return guid;
};
I call it with:
var thisTest.guid1 = helpers.guid();
var thisTest.guid2 = helpers.guid();
The problem is each time I refer to thisTest.guid1 it's a different guid. I need to set the object property to a permanent value and I'm not sure how to do that. I've tried adding a closure but couldn't get it to work.
Edit: to clarify, i need to be able to generate multiple guids and assign each one to a different variable. Right now each time I refer to a variable i get a new guid as it presumably calls the function again and returns a new value. I need "guid1" and "guid2" to be the same values each time then are used.
Question title is much simpler than unnecessarily complicated code example and text with it ... Let's use much simpler code.
var seed = 1 ;
function generate () {
return seed++ ;
}
var a = generate() ;
alert(a + "\n" + a + "\n" + a ) ;
This of course shows "1" three times ... And it will, regardless of is it an object property or a variable. Return value of the function is kept in the memory because it is referenced by the variable a. Object property of course will behave the same:
var a = { b : generate() };
alert( a.b + "\n" + a.b + "\n" + a.b ) ;
This will show "1" three times again. Likewise each call to generate() will yield new value.
var a = {b:generate(), c:generate(), d:generate() };
alert( a.b + "\n" + a.c + "\n" + a.d ) ;
This will output "1", "2" and "3". Each call to function returns a value which is referenced by different object property, thus we have three different values.
If I am understanding correctly you could use 2 functions:
1 - a function to generate the GUID and then store it somewhere, like
in a hidden control somewhere on your form, so you can get it later
2- a function that retrieves the value of your hidden control.

Reading a Javascript Object

How do I read a Javascript Object when I don't know what's in it?
I've been working on node.js and have a variable for which I really don't know what's in it. When I try sys.puts:
sys.puts(headers) // returns [object Object]
If there was something like a print_r in javascript, that would have been fine.
You can loop over its properties with
for (var item in headers)
{
// item is the name of the property
// headers[item] is the value
}
example at http://www.jsfiddle.net/gaby/CVJry/3/ (requires console)
If you want to limit the results to direct properties (not inherited through the prototype chain) then use as well the hasOwnProperty method.
example at http://www.jsfiddle.net/gaby/CVJry/2/
Most web browsers can use the JSON-object to print the contents of an object,
writeln(JSON.stringify(your_object));
If that fails, you can create your own stringifier;
var stringify = function(current) {
if (typeof current != 'object')
return current;
var contents = '{';
for (property in current) {
contents += property + ": " + stringify(current[property]) + ", ";
}
return contents.substring(0, contents.length - 2) + "}";
}
var my_object = {my_string: 'One', another_object: {extra: 'Two'}};
writeln(stringify(my_object));
You can loop through your object to know its properties & their values
Suppose your object is
var emp = {
name:'abc',
age:12,
designation:'A'
}
Now you can read its details in JS
for(property in emp ){
alert(emp[property] + " " +property);
}
If you have firebug in added in your Firefox browser, open it & write either in JS or JS window in Firebug console.
console.log(a);
If you need it just to check what's in an object (ie, it's relevant to you for some reason, but you don't need that functionality in your script), you can just use Firebug to get the object and check exactly what's in it.

Categories

Resources