配列オブジェクトを作成した後、配列をループするつもりはありません。この作業を行うためにアンダースコア _.each 関数を使用しています。突然、私のコードで予期しないことが起こりました。次のコードを検討してください
var _ = require('underscore');
var myArray = [ 'RE', 'FR', 'TZ', 'SD'];
var traverse = function (element, index, list) {
console.log(para1);
console.log(element);
}
var func1 = function (para1) {
_.each(myArray, traverse);
}
func1('test');
出力として、エラーメッセージが表示されました
Volumes/Develop/node_sample/scope.js:7
console.log(para1);
^
ReferenceError: para1 is not defined
at traverse (/Volumes/Develop/node_sample/scope.js:7:14)
at Array.forEach (native)
at Function._.each._.forEach (/Volumes/Develop/node_sample/node_modules/underscore/underscore.js:79:11)
at func1 (/Volumes/Develop/node_sample/scope.js:13:4)
at Object.<anonymous> (/Volumes/Develop/node_sample/scope.js:16:1)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
traverse 関数が para1 変数を認識しないのはなぜですか? 私は func で _.each 関数を実行します。私の意見では、スコープを使用する必要があります。
しかし、このようにコードを書くと、スコープ チェーンは正常に動作します。
var _ = require('underscore');
var myArray = [ 'RE', 'FR', 'TZ', 'SD'];
var func1 = function (para1) {
_.each(myArray, function (element, index, list) {
console.log(para1);
console.log(element);
});
}
func1('test');