😆
【JavaScript】someメソッドとは(備忘録)
1.some()メソッドとは
配列内のいずれかの要素が、条件に合致しているかを判定する際に使用します。
戻り値は、trueかfalseです。
someメソッドの文法
配列名.some(コールバック関数)
2.サンプルプログラム
〇例1:
Sample_1.js
const array = [1, 2, 3, 4, 5];
// 配列の要素に2の倍数が存在するか
const result = (value) => value % 2 === 0;
console.log(array.some(result));
実行結果
true
〇例2:
Sample_2.js
const array = [1, 2, 3, 4, 5];
// 配列の要素に6以上の値が存在するか
const result = (value) => value >= 6;
console.log(array.some(result));
実行結果
false
〇例3:return文を使用
Sample_3.js
const array = [1, 2, 3, 4, 5];
// 配列の要素に2の倍数が存在するか
const result = array.some(function(value){
return value % 2 === 0;
});
console.log(result);
実行結果
true
〇例4:return文を忘れた場合
Sample_4.js
const array = [1, 2, 3, 4, 5];
// 配列の要素に2の倍数が存在するか
const result = array.some(function(value){
value % 2 === 0;
});
console.log(result);
実行結果
false
〇例5:
Sample_5.js
const fruit = ["リンゴ", "バナナ", "桃", "柿", "メロン"];
function listCheck(array, test_data) {
// ブドウが配列に存在するかチェック
return array.some((array_value) => test_data === array_value);
}
console.log(listCheck(fruit, "ブドウ"));
実行結果
false
3.参考
4.その他
・実行環境
Discussion