const colors = ["red", "green", "blue", "red"];

/*
 * 注意してください!
 * 配列ではインデックスは0から始まります。
 * 最初の要素のインデックスは0で、2番目の要素のインデックスは1です。
*/

// 配列colorsから要素「red」を検索し、最初に検索された(出現した)要素のインデックスを返します。
const red = colors.indexOf("red");
console.log(red); // 出力:0

// 配列colorsから引数として渡された要素「yellow」を見つけることができないため、-1を返します。
const yellow = colors.indexOf("yellow");
console.log(yellow); // 出力:-1

const blue = colors.indexOf("blue", 1);
// 2番目の引数は検索を開始するインデックスです。
// この引数はオプションで、省略した場合は先頭(0)から検索します。
// 引数の値が1であるため、2番目の要素から検索した場合でも要素「blue」は検索対象となり、
// 配列の先頭(インデックス0)から数えた要素「blue」のインデックスは2になります。

console.log(blue); // 出力:2
arr.indexOf(searchElement[, fromIndex])
/*
 * 引数として渡された要素が配列内に重複して存在する場合、
 * 最初に検索された(出現した)要素のインデックスを返します。
*/
const colors = ["red", "green", "green", "blue"];

// 配列colorsから要素「green」を検索し、最初に検索された(出現した)要素のインデックスを返します。
const green = colors.indexOf("green");

// 配列colorsには要素「green」が2つ存在します。
// インデックス1と2にあります。
// しかし、最初に検索された要素のインデックスである1を返します。
console.log(green); // 出力:1;


/*
 * arr.indexOf(searchElement[, fromIndex])
 *
 * オプション(任意)で指定するfromIndexが負の値の場合、
 * 配列の末尾から逆方向にカウントされます。
 * ただし、検索はあくまで左から右へ行われます。
*/
const fruits = ["apple", "bannana", "orange", "mango"];
const index = fruits.indexOf("mango", -2);

console.log(index); // 出力:3
// fromIndexの値は-2です。
// 配列の末尾から逆にカウントされるため、
// 末尾から2番目の要素である「orange」から検索を開始します。
// ただし、検索自体は左から右へ行われます。
// 探している要素「mango」は「orange」の右側に存在するため、
// fruits配列における「mango」のインデックスである3が出力されます。
const arr = [1, 2, NaN, 4, 5];
console.log(arr.indexOf(NaN)); // 出力: -1
const colors = ["red", "green", "blue"];
const red = colors.indexOf("Red");

// 大文字の「R」と小文字の「r」は区別されます。
console.log(red); // 出力:-1
const arr = [1, 2, 3, 4, 5];
const element = 3;

if (arr.indexOf(element) !== -1) {
    console.log(`${element}は配列に存在します。`);
} else {
    console.log(`${element}は配列に存在しません。`);
}

// 出力:`3は配列に存在します。`
const arr = [1, 2, 2, 3, 4, 4, 5];
const uniqueArr = [];

arr.forEach(element => {
    if (uniqueArr.indexOf(element) === -1) {
        uniqueArr.push(element);
    }
});

console.log(uniqueArr); // 出力: [1, 2, 3, 4, 5]
const arr = [1, 2, 2, 3, 4, 4, 5];
const uniqueArr = Array.from(new Set(arr));

console.log(uniqueArr); // 出力:[1, 2, 3, 4, 5]
const arr = [1, 2, 3, 4, 5];
const element = 3;
const startIndex = 1;
const endIndex = 3;
const subArray = arr.slice(startIndex, endIndex + 1);

if (subArray.indexOf(element) !== -1) {
    console.log(`${element}は指定した範囲内で配列に存在します。`);
} else {
    console.log(`${element}は指定した範囲内で配列に存在しません。`);
}

// 出力:「3は指定した範囲内で配列に存在します。」