functiontrimSections(header, body, footer) { for (var i = 0, n = header.length; i < n; i++) { header[i] = header[i].trim(); } for (var i = 0, n = body.length; i < n; i++) { body[i] = body[i].trim(); } for (var i = 0, n = footer.length; i < n; i++) { footer[i] = footer[i].trim(); } }
functiontest() { var x = 'var', result = []; result.push(x); try { throw'exception'; } catch (x) { x = 'catch'; } result.push(x); return result; } console.log(test()); // [ 'var', 'var' ]
4、闭包存储的是其外部变量的引用而不是值
1 2 3 4 5 6 7 8 9 10 11 12 13 14
functionwrapElements(a) { var result = [], i, n; for (i = 0, n = a.length; i < n; i++) { result[i] = function() { return a[i]; }; } return result; } var wrapped = wrapElements([10, 20, 30, 40, 50]);
var f = wrapped[0]; console.log(f()); // undefined
functionwrapElements(a) { var result = [], i, n; for (i = 0, n = a.length; i < n; i++) { (function(j) { result[i] = function() { return a[j]; }; })(i); } return result; }