some
function isEven(value) {
return value % 2 === 0;
}
var array = [1, 2, 3, 4, 5];
// Array.prototype.forEach()の場合、
// 途中でreturnを行ったとしてもループは抜けられず、
// 最後の要素まで処理が実行される
array.forEach(function (value, index) {
console.log(index + '番目 : ' + value);
if (isEven(value)) return;
});
// 0番目 : 1
// 1番目 : 2
// 2番目 : 3
// 3番目 : 4
// 4番目 : 5
// Array.prototype.some()の場合、
// ループを抜けたいタイミングでtrueをreturnすることで、
// それ以降の要素では処理が実行されない
array.some(function (value, index) {
console.log(index + '番目 : ' + value);
return isEven(value);
});
// 0番目 : 1
// 1番目 : 2
// 値が20歳以上かどうかをtrueかfalseで返す関数
function isAdult(age) {
return age >= 20;
}
var applicants = [
{
name: '山田太郎',
age: 15
},
{
name: '田中花子',
age: 18
},
{
name: '鈴木一',
age: 21
}
];
var anyAdults = applicants.some(function (applicant) {
return isAdult(applicant.age);
});
if (!anyAdults) {
window.alert('保護者の同伴が必要です');
}
else {
// 申し込みの処理
}