0
1

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 1 year has passed since last update.

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

Last updated at Posted at 2022-09-21

こういうコードがあったとする。
これをスッキリとさせたい。(今は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;

終わり。

0
1
2

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?