| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf | [Back] [Original] |
Get to know MDN better
const beasts = ["ant", "bison", "camel", "duck", "bison"];
console.log(beasts.indexOf("bison"));
// : 1
// Start from index 2
console.log(beasts.indexOf("bison", 2));
// : 4
console.log(beasts.indexOf("giraffe"));
// : -1
indexOf(searchElement)
indexOf(searchElement, fromIndex)
searchElementfromIndex -array.length <= fromIndex < 0 fromIndex + array.length fromIndex < -array.length fromIndex 0 fromIndex >= array.length -1 searchElement `-1``
indexOf() searchElement === NaN indexOf() searchElement NaN -1
indexOf()
const array = [2, 9, 9];
array.indexOf(2); // 0
array.indexOf(7); // -1
array.indexOf(9, 2); // 2
array.indexOf(2, -1); // -1
array.indexOf(2, -3); // 0
indexOf() NaN
const array = [NaN];
array.indexOf(NaN); // -1
const indices = [];
const array = ["a", "b", "a", "c", "a", "d"];
const element = "a";
let idx = array.indexOf(element);
while (idx !== -1) {
indices.push(idx);
idx = array.indexOf(element, idx + 1);
}
console.log(indices);
// [0, 2, 4]
function updateVegetablesCollection(veggies, veggie) {
if (veggies.indexOf(veggie) === -1) {
veggies.push(veggie);
console.log(`New veggies collection is: ${veggies}`);
} else {
console.log(`${veggie} already exists in the veggies collection.`);
}
}
const veggies = ["potato", "tomato", "chillies", "green-pepper"];
updateVegetablesCollection(veggies, "spinach");
// New veggies collection is: potato,tomato,chillies,green-pepper,spinach
updateVegetablesCollection(veggies, "spinach");
// spinach already exists in the veggies collection.
indexOf()
console.log([1, , 3].indexOf(undefined)); // -1
indexOf() this length length
const arrayLike = {
length: 3,
0: 2,
1: 3,
2: 4,
3: 5, // length 3 indexOf()
};
console.log(Array.prototype.indexOf.call(arrayLike, 2));
// 0
console.log(Array.prototype.indexOf.call(arrayLike, 5));
// -1
| ECMAScript 2027 LanguageSpecification # sec-array.prototype.indexof |
Arrayat()concat()copyWithin()entries()every()fill()filter()find()findIndex()findLast()findLastIndex()flat()flatMap()forEach()includes()indexOf()join()keys()lastIndexOf()map()pop()push()reduce()reduceRight()reverse()shift()slice()some()sort()splice()toLocaleString()toReversed()toSorted()toSpliced()toString()unshift()values()with()[Symbol.iterator]()Object/Function| Web Proxy Viewer | New URL | Original Page |