1

I have a small question:

I have a function in javascript.

var func = function(variable)
{
    result = variable;
}

If I call

func(rabbit);

I need the result to be "rabbit".

I cannot figure out how to put the variable between the two quotes.

Linus Kleen
  • 33,871
  • 11
  • 91
  • 99
Kat
  • 668
  • 2
  • 11
  • 24

5 Answers5

1

Assuming rabbit is supposed to be a string:

func("rabbit");

If rabbit is actually a variable, then there's no way to do this because the variable (meaning the implementation's representation of a variable) isn't actually passed to the function, but rather its value is.

Cameron
  • 96,106
  • 25
  • 196
  • 225
1

Actually there's an ancient way to retrieve the variable name.

var func = function(variable)
{
    console.log(variable); // outputs "white"
    console.log(arguments.callee.caller.toString().match(/func\((.*?)\)/)[1]); // outputs "rabbit"
}

rabbit = 'white';

func(rabbit);

See it running http://jsfiddle.net/Q55Rb/

lukedays
  • 323
  • 1
  • 10
1

You could do this

function whatever(input) {
  return '\"' + input + '\"';
}

result should be in quotes

Kyle.S
  • 9
  • 7
0

I could not tell from your question whether you wanted "rabbit" to be the property name, or the value. So here is both:

var func = function(variable) {
    window[variable] = 'abc';    // Setting the variable as what is passed in
    window.result = variable;    // Normal
}

func('rabbit');    // Will set both window.rabbit to 'abc', and window.result to 'rabbit'

I wouldn't advise setting global variables, though. More info

Community
  • 1
  • 1
Julian H. Lam
  • 25,501
  • 13
  • 46
  • 73
0

Ok I thought that was my problem. Now I'm pretty sure that's not it but I have no clue what it is then.

I have this in my function:

defaults = {title :{'pan':-1,'left':0,'volume':0.30,'top':111}}; 

Where title is a variable from the function. But as a result I get title in defaults instead of the actual title stored in the variable named title. Do you understand me?

Kat
  • 668
  • 2
  • 11
  • 24