search
LoginSignup
1

posted at

updated at

【JavaScript】if文の中でgotoしたい

こういうコードがあったとする。
これをスッキリとさせたい。(今はa, b, cしかないが、後々d, e, f…などと追加されたとき面倒だから)

if (a.isHoge111) {
	a.hoge111();
}
else if (b.isHoge111) {
	b.hoge111();
}
else if (c.isHoge111) {
	c.hoge111();
}
else if (a.isHoge222) {
	a.hoge222();
}
else if (b.isHoge222) {
	b.hoge222();
}
else if (c.isHoge222) {
	c.hoge222();
}

if (a.isHoge333) {
	a.hoge333();
}
else if (b.isHoge333) {
	b.hoge333();
}
else if (c.isHoge333) {
	c.hoge333();
}
else if (a.isHoge444) {
	a.hoge444();
}
else if (b.isHoge444) {
	b.hoge444();
}
else if (c.isHoge444) {
	c.hoge444();
}

if (a.isHoge555) {
	a.hoge555();
}
else if (b.isHoge555) {
	b.hoge555();
}
else if (c.isHoge555) {
	c.hoge555();
}
else if (a.isHoge666) {
	a.hoge666();
}
else if (b.isHoge666) {
	b.hoge666();
}
else if (c.isHoge666) {
	c.hoge666();
}

return;

もしJavaScriptにgoto文があれば次のように書けるのだが…ないので無理

const list = [a, b, c];

for (const x of list) {
	if (x.isHoge111) {
		x.hoge111();
		goto FUGA;
	}
}

for (const x of list) {
	if (x.isHoge222) {
		x.hoge222();
		goto FUGA;
	}
}

FUGA:

for (const x of list) {
	if (x.isHoge333) {
		x.hoge333();
		goto PIYO;
	}
}

for (const x of list) {
	if (x.isHoge444) {
		x.hoge444();
		goto PIYO;
	}
}

PIYO:

for (const x of list) {
	if (x.isHoge555) {
		x.hoge555();
		return;
	}
}

for (const x of list) {
	if (x.isHoge666) {
		x.hoge666();
		return;
	}
}

return;

しょうがないのでこう書く。

const list = [a, b, c];

(() => {
	for (const x of list) {
		if (x.isHoge111) {
			x.hoge111();
			return;
		}
	}

	for (const x of list) {
		if (x.isHoge222) {
			x.hoge222();
			return;
		}
	}
})();

(() => {
	for (const x of list) {
		if (x.isHoge333) {
			x.hoge333();
			return;
		}
	}

	for (const x of list) {
		if (x.isHoge444) {
			x.hoge444();
			return;
		}
	}
})();

(() => {
	for (const x of list) {
		if (x.isHoge555) {
			x.hoge555();
			return;
		}
	}

	for (const x of list) {
		if (x.isHoge666) {
			x.hoge666();
			return;
		}
	}
})();

return;

終わり。

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
What you can do with signing up
1