这个javascript函数可能吗? [英] It this javascript function possible?

查看:75
本文介绍了这个javascript函数可能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

调试时我经常写一些像 console.log(foo:+ foo +,bar:+ bar)是否可以写一个函数 logValues(foo,bar)哪个会提供相同的输出?基本上我在问是否有办法从变量变为该变量的名称。我是否必须使用索引产生 [0]来设置参数数组的循环:'foo的值,[1]:'bar的值'

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'

感谢阅读

推荐答案

(这些选项都没有直接回答这个问题;但是应该为你要做的事情提供更好的选择)

(none of these options directly answer the question; but should give better alternatives for what you're trying to do)

WebKit的检查员(我假设Firebug)允许你记录复杂的类型,不需要写帮手吧!

只需 console.log(foo,bar)你就是组。或者 console.log({foo:foo,bar:bar})如果你想在输出中输入变量名。

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.

替代答案:

您可能会考虑一个只需要一个对象并将其吐出的助手 - 它不会节省太多如果有的话,打字;但结果是更可读的代码与记录的输出非常匹配。

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(", "));
};

然后将其称为:

logValues({foo: 1, bar: "asdf"})

你看到了:

foo: 1, bar: asdf

选项#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));
}

这篇关于这个javascript函数可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆