8
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

forとarray.forEachのスコープ

Posted at

javascriptでは、forブロックで宣言した変数はforの外に出る。
forEachはループするのにcallback関数を利用しているため、変数は関数のローカルスコープから出ない。

var arr = [1,2,3,4,5];
for(var i = 0; i < arr.length; i++){
  console.log('v:', v);
  var v = arr[i];
};
console.log('out v:', v);
console.log('--------------------------');

arr.forEach(function(v){
  console.log(val);
  var val = v;
});
console.log('out val:',val);

実行結果。

v: undefined
v: 1
v: 2
v: 3
v: 4
out v: 5
--------------------------
undefined
undefined
undefined
undefined
undefined

console.log('out val:',val);
                       ^
ReferenceError: val is not defined

forブロックのconsole.log('v:', v);は1回前のforループの値を利用できるようだ。

8
4
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?