Skip to content

Instantly share code, notes, and snippets.

@aoi0308
Created September 7, 2013 02:46
Show Gist options
  • Save aoi0308/6472388 to your computer and use it in GitHub Desktop.
Save aoi0308/6472388 to your computer and use it in GitHub Desktop.
JavaScriptの文字列をforEachでループ処理する。
// 処理対象の文字列
var str = "Hello, JavaScript!";
// 通常のfor文で行う
for (var i = 0; i < str.length; i++) {
console.log(str[i]);
}
// 一応動くけど、まぁやめた方が良い
for (var i in str) {
console.log(str[i]);
}
// ArrayのforEachを借りる
Array.prototype.forEach.call(str, function(s) {
console.log(s);
});
// これでも同じ
[].forEach.call(str, function(s) {
console.log(s);
});
// Underscoreでも大丈夫
_.each(str, function(s) {
console.log(s)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment