调试代码时,常常需要将数据读出,这个小工具或许能帮上忙.
- <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
- <html xmlns=“http://www.w3.org/1999/xhtml”>
-
- <head>
- <meta http-equiv=“Content-Type” content=“text/html; charset=utf-8″ />
- <title>Untitled 1</title>
- <script type=“text/javascript”>
- <!–
-
- function tojson(target) {
- var str = [],
- i,
- len;
- if (Object.prototype.toString.call(target)===‘[object Array]‘) {
- for (i=0,len=target.length; i<len; i++) {
- str.push(tojson(target[i]));
- }
- str = ‘['+str.join(',')+']‘;
- }
- else if (!!target && (typeof target == ‘object’ || typeof target == ‘function’)) {
- for (i in target) {
- if (!i && !target[i]) {
- continue;
- }
- else {
- str.push(‘”‘+String(i).toString().replace(/\”/g,‘\\”‘)+‘”:’+tojson(target[i]));
- }
- }
- str = ‘{‘+str.join(‘,’)+‘}’;
- }
- else if ( target === undefined){
- str = ‘undefined’;
- }
- else if ( target === null){
- str = ‘null’;
- }
- else {
- str = ‘”‘+String(target).toString().replace(/\”/g,‘\\”‘)+‘”‘;
- }
- return str;
- }
-
- function doit(){
-
- alert(tojson({‘a’:[{'"':123,'c':undefined}]}));
- }
-
-
- </script>
- </head>
-
- <body><button type=“button” onclick=“doit()”>doit</button>
-
- </body>
-
- </html>
转载自:http://blog.iamzsx.me/show.html?id=83004
在python中我们可以在一个函数中再定义一个函数,而内部的函数可以使用外部的局部变量。如下面的代码:
- def test():
- a=1
- def test1():
- print a
- a=2
- test1()
- a=3
- test1()
-
- test()
输出结果是
这是一个很方便的特性,但是需要注意的是,在内部的函数中无法修改外部的局部变量。
例如下面的代码,就会报错:
- def test():
- a=1
- def test1():
- a+=2
- print a
- a=2
- test1()
- a=3
- test1()
-
- test()
Unbound LocalError: local variable ‘a’ referenced before assignment
在python的FAQs中提到了这件事,如果一个变量在函数中被赋值,那么就被视为局部变量,也就是test1里面的a此时被认为是test1自己的局部变量,而我们没有给a赋值就使用了a,于是出现上面的异常信息。这也就是我前面说“无法修改”的原因,并不是不允许修改,而是无法使用到这个外部的变量(test的a是外部变量,test1中的a被当成了局部变量,在test1中我们看不见test中的a)。
在python 3.0之后,我们可以通过给一个变量加nonlocal标识符来告诉解释器,不要把这个变量当成函数内部的局部变量,从而可以修改外部变量。这也更证明了前面的无法修改的观点。3.0代码如下:
- def test():
- a=1
- def test1():
- nonlocal a
- a+=2
- print(a)
- a=2
- test1()
- a=3
- test1()
-
- test()
关于python的闭包实现,请参考http://linluxiang.javaeye.com/blog/789946