Array.prototype.indexOf()
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison'));
// Expected output: 1
// Start from index 2
console.log(beasts.indexOf('bison', 2));
// Expected output: 4
console.log(beasts.indexOf('giraffe'));
// Expected output: -1
String.prototype.indexOf()
const paragraph = "I think Ruth's dog is cuter than your dog!";
const searchTerm = 'dog';
const indexOfFirst = paragraph.indexOf(searchTerm);
console.log(`The index of the first "${searchTerm}" is ${indexOfFirst}`);
// Expected output: "The index of the first "dog" is 15"
console.log(
`The index of the second "${searchTerm}" is ${paragraph.indexOf(
searchTerm,
indexOfFirst + 1,
)}`,
);
// Expected output: "The index of the second "dog" is 38"
前端工程师、程序员