LoginSignup
2

More than 5 years have passed since last update.

for if のイディオム

Posted at

RaphaelJS のソースを見ていると、for と if を続けた見慣れないイディオムが使われています。

for (var i = 0; i < 10; i++) if (i % 3 === 0) {
  console.log(i);
}
// 0
// 3
// 6
// 9

ループのフィルタリングとして機能します。特別な文法というだけではなく、for{} を省略しているだけです。

for (var i = 0; i < 10; i++) {
  if (i % 3 === 0) {
    console.log(i);
  }
}

ちなみに {} の省略は JSLint を通りません。

RaphaelJS では、オブジェクトの直接のプロパティだけをループしたい時などによく使われています。

function Foo() {
  this.foo = 'Foo!';
}
Foo.prototype.bar = 'Bar!';

var obj = new Foo();

for (var key in obj) {
  console.log(key + ': ' + obj[key] + ' is obj\'s property.');
}
// foo: Foo! is obj's property.
// bar: Bar! is obj's property.

var has = 'hasOwnProperty';
for (var key in obj) if (obj[has](key)) {
  console.log(key + ': ' + obj[key] + ' is obj\'s own property.');
}
// foo: Foo! is obj's own property.

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
2