Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
113 views
in Technique[技术] by (71.8m points)

javascript - How to console log the name of a variable/function?

I want to do this: log(variableOrFunction)

And be able to produce this: variableOrFunction: actualValue.

I tried this:

export const log = (value) => {
  console.log('' + value + ':', value)
  console.log(value)
}

But I get this instead: [object Object]:

What's the correct of doing this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can log them with a pair of braces around them ({}), which will create an object with the name of the variable as the key:

function someFunction() {};

const someOtherFunction = () => {};

const someValue = 9;

console.log({someFunction});
console.log({someOtherFunction});
console.log({someValue});

const renamed = someFunction;

console.log({renamed})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...