javascript indexOf() - 字符串和数组方法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript indexOf() - 字符串和数组方法相关的知识,希望对你有一定的参考价值。

// The indexOf() method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex. Returns -1 if the value is not found.
// Case Sensitive

// STRING.indexOf()
let str = 'Winter is coming';
let position = str.indexOf('coming');

console.log(position); // 10

// Count occurences of a letter in a string
let str = 'Winter is coming';
let position = str.indexOf('i');
let count = 0;

while(position !== -1) {
  count++;
  position = str.indexOf("i", position + 1)
}

console.log(count); // 3

// ------------------------------------------------------------------ //

// ARRAY.indexOf() - array.indexOf(item, start)
let pieces = ['king', 'queen', 'rook', 'knight', 'bishop'];

console.log(pieces.indexOf('rook')); // 2

// Finding all the occurrences of an element
let indices = [];
let array = ['a', 'b', 'a', 'c', 'a', 'd'];
let element = 'a';
let ids = array.indexOf(element);
while (ids != -1) {
  indices.push(ids);
  ids = array.indexOf(element, ids + 1);
}
console.log(indices); // [0, 2, 4]

以上是关于javascript indexOf() - 字符串和数组方法的主要内容,如果未能解决你的问题,请参考以下文章

JavaScript indexOf() 方法

javascript indexOf() - 字符串和数组方法

JavaScript indexOf() 方法和 lastIndexOf() 方法

JavaScript indexOf() 方法和 lastIndexOf() 方法

浅析JavaScript的字符串查找函数:indexOf和search

javascript 检查字符串与indexOf的相似性