字符串indexof方法_探索JavaScript中的字符串和数组的indexOf方法

news/2024/7/7 9:46:53

字符串indexof方法

When you need to find an element in an array or a string, indexOf() is one of your best friends.

当您需要在数组或字符串中查找元素时, indexOf()是您最好的朋友之一。

数组中的indexOf (indexOf   in Arrays)

Code first, explanation later:

代码优先,稍后解释:

Module: findSpencer.js
模组:findSpencer.js
const zoo = ['🐒', '🦄', '🐊', '🐸', '🐙'];
const spencersIndex = zoo.indexOf('🐊');
// spencersIndex === 2
const spencer = zoo[spencersIndex];
// spencer === '🐊'

In its simplest version, the indexOf method takes one argument which is the element we are trying to find. Then it returns the index of the first element it finds in the array which satisfies el === target. This means that even if there are two matches in your array, indexOf will only return one result. The result is the first occurrence in the array (reading the array from left to right).

在最简单的版本中, indexOf方法采用一个参数,这是我们要查找的元素。 然后,它返回满足el === target的数组中找到的第一个元素的索引。 这意味着即使数组中有两个匹配项,indexOf也只会返回一个结果。 结果是数组中的第一个匹配项(从左到右读取数组)。

When no item in the array satisfies the el === target check, the value of -1 is returned.

当数组中没有项满足el === target检查时,返回值-1

But let’s say we are also looking for Skyler (Spencer’s sister). Then we can add an extra optional argument to start the search from a different index.

但是,假设我们也在寻找Skyler(Spencer的姐姐)。 然后,我们可以添加一个额外的可选参数,以从其他索引开始搜索。

Module: findSkyler.js
模块:findSkyler.js
const zoo = ['🐒', '🦄', '🐊', '🐸', '🐙',  '🐊']; // Skyler just arrived!
const spencersIndex = zoo.indexOf('🐊'); // === 2 same as before

// We start searching after 
const skylersIndex = zoo.indexOf('🐊', spencersIndex + 1);
// skylersIndex === 5

We can also create a method on the Array prototype that returns all the indices based on indexOf.

我们还可以在Array原型上创建一个方法,该方法返回基于indexOf的所有索引。

Module: indicesOf.js
模块:indexsOf.js
// Try to think of ways to make indicesOf more performant
Array.prototype.indicesOf = function (target) {
  const result = [];
  let currentIndex = 0;
  while(true) {
    // here this ===  the array on which we call `indicesOf`
    const targetIndex = this.indexOf(target, currentIndex);
    if (targetIndex == -1)
      break;

    result.push(targetIndex);

    currentIndex = targetIndex +1;
  }

  return result;
}
const zoo = ['🐒', '🦄', '🐊', '🐸', '🐙',  '🐊']; // Skyler just arrived!
const alligatorsIndices = zoo.indicesOf('🐊');
// alligatorsIndices returns [2, 5]

indexOf找不到什么? (What Can’t You Find With indexOf?)

You might have noticed that we interrupt the search by using triple equal comparison el === target which is a strict equality comparison. This means, for example, that we can’t test for arrays, objects or functions other than by reference.

您可能已经注意到,我们使用三重相等比较el === target这是严格的相等比较)中断了搜索。 例如,这意味着除了引用之外,我们无法测试数组,对象或函数。

const simpleArray = [1, 2, 3];
const simpleFunction = () => {console.log('hey')};
const simpleObject = {alligator: 'cage'};

const compositeArray = [simpleArray, simpleFunction, simpleObject];

// These all work as expected because we compare by reference
compositeArray.indexOf(simpleArray); // returns 0
compositeArray.indexOf(simpleFunction); // returns 1
compositeArray.indexOf(simpleObject); // returns 2

// These won't work 
compositeArray.indexOf([1, 2, 3]); // returns -1
compositeArray.indexOf(() => {console.log('hey')}); // returns -1
compositeArray.indexOf({alligator: 'cage'}) // returns -1

深度索引 (A Deep indexOf)

Let’s say we want to create a utility to also check for objects, arrays and functions recursively:

假设我们要创建一个实用程序来递归检查对象,数组和函数:

Module: inDepthIndexOf.js
模组:inDepthIndexOf.js
Array.prototype.deepIndexOf = function (target) {
  // If the target is an object, array or a function, we give it a special treatment
  if (typeof target === 'object' || typeof target === 'function') {
    // We stringify the target 
    const searchTarget = target.toString()
    // We loop through all of the elements of the array
    for (let index = 0; index < this.length; index++){
      const element = this[index]
      // We check if the element in the array is an object or a function AND if so we check if its' stringified value is equal to our target
      if ((typeof element === 'object' || typeof target === 'function') && element.toString() === searchTarget) {
        // if we have a match we interrupt the loop and return the index
        return index
      }
    }
    // if nothing matched we return -1
    return -1
  }
  return this.indexOf(target)
}

const simpleArray = [1, 2, 3];
const simpleFunction = () => {console.log('hey')};
const simpleObject = {alligator: 'cage'};

const compositeArray = [simpleArray, simpleFunction, simpleObject];

// These all work as expected because we compare by reference
compositeArray.deepIndexOf(simpleArray); // returns 0
// ... You know the rest
// These will work!
compositeArray.deepIndexOf([1, 2, 3]); // returns 0
compositeArray.deepIndexOf(() => {console.log('hey')}); // returns 1
compositeArray.deepIndexOf({alligator: 'cage'}) // returns 2

There are many ways to improve this code. If you have some time on your hands, try to think of how to make it more accurate and performant. I’d love to read your ideas on Twitter.

有很多方法可以改进此代码。 如果您有时间,请尝试思考如何使其更加准确和高效。 我很想在Twitter上阅读您的想法。

性能 (Performance)

Using indexOf is much slower than simply doing a for loop. That doesn’t mean that indexOf is slow. If your array is small you will never see the difference between indexOf() or a for loop. If your array is so big that you can notice a difference between the two methods, then you should probably wonder why your array is so big and how you could optimize the search. You can find performance benchmarks on JSPerf.

使用indexOf比执行for loop要慢得多。 这并不意味着indexOf很慢。 如果您的数组很小,您将永远看不到indexOf()或for循环之间的区别。 如果数组太大,您会注意到这两种方法之间的差异,那么您可能想知道为什么数组这么大,以及如何优化搜索。 您可以在JSPerf上找到性能基准 。

var spencersIndex
// This is faster than indexOf('🐊') but it is much uglier
for(var index = 0; index < zoo.length; index ++) {
  if (zoo[index] === '🐊')
    spencersIndex = index
}
// spencers Index === 2

字符串中的indexOf (indexOf in Strings)

You can port all the logic from Array.indexOf to this section. Let’s code!

您可以将所有逻辑从Array.indexOf到此部分。 让我们编码吧!

Module: whereIsSpencer.js
模块:whereIsSpencer.js
const whereIsSpencer = "We are all looking for Spencer the alligator. Spencer is a dear friend. Lookout here comes 🐊!"

const spencersIndex = whereIsSpencer.indexOf('Spencer');
// spencersIndex ===  23

// to find find the second occurence of 'Spencer',
// we need to add one to the position of spencer #1
const secondSpencerIndex = whereIsSpencer.indexOf('Spencer', spencersIndex + 1);
// secondSpencerIndex ===  46

const alligatorIndex = whereIsSpencer.indexOf('🐊');
// alligatorIndex ===  91

// Be careful the search is case sensitive!
const lowerCaseSpencer = whereIsSpencer.indexOf('spencer');
// lowerCaseSpencer === -1

Now we can create the same indicesOf function for Array.prototype.string.

现在,我们可以为Array.prototype.string创建相同的indicesOf函数。

Module: indicesOfStrings.js
模块:indexsOfStrings.js
// This is a bit more concise than the previous indicesOf function
// But it is exactly the same logic
String.prototype.indicesOf = function (target) {
  let currentIndex = this.indexOf(target);
  const allIndices = []
  while(currentIndex != -1) {
    allIndices.push(currentIndex);
    currentIndex =  this.indexOf(target, currentIndex +1 );
  }

  return allIndices;
}

const whereIsSpencer = "We are all looking for Spencer the alligator. Spencer is a dear friend. Lookout here comes 🐊!";

const spencerIndices = whereIsSpencer.indicesOf('Spencer');
// spencerIndices equals [23, 46]

I hope you had fun reading this post! If you have any suggestions, questions or comments feel free to ask away on Twitter.

希望您在阅读这篇文章时玩得开心! 如果您有任何建议,问题或评论,请随时在Twitter上提问。

翻译自: https://www.digitalocean.com/community/tutorials/js-indexof

字符串indexof方法


http://www.niftyadmin.cn/n/3648926.html

相关文章

Android(Lollipop/5.0) Material Design(八) 保持兼容性

Define Alternative Styles 定义替代样式 让你的app&#xff0c;使用Material Design的主题运行在支持它的设备上&#xff0c;并在早期版本的设备上可以运行较早的主题&#xff1a;1. 在res/values/styles.xml 定义一个主题继承较早的主题2. 在res/values-v21/styles.xml 定义…

软件测试管理--第一章 1.1节

第一部分 基础篇第1章 测试管理概论“我们这个项目的测试人员太少了&#xff01;”“能否给我们提供一台新的测试服务器&#xff01;”“需要延长一个星期的进度才可以完成测试工作&#xff01;”“开发人员压根就没有修改缺陷&#xff01;我们还测试什么&#xff01;”“怎…

如何在CentOS 7上安装和使用PostgreSQL

介绍 (Introduction) Relational database management systems are a key component of many web sites and applications. They provide a structured way to store, organize, and access information. 关系数据库管理系统是许多网站和应用程序的关键组成部分。 它们提供了一…

23种设计模式之模板方法模式(template method)

场景&#xff1a;我们去银行&#xff0c;一般分三步&#xff0c;取号排队&#xff0c;办理具体的业务 &#xff0c;反馈评分。只有办具体的业务我们是不确定的&#xff0c;今天我有可能取钱&#xff0c;明天有可能存钱&#xff0c;也有可能后天去和妹子搭讪。这时候我们就可以做…

Android 5.0——Material Design详解(动画篇)

Material Design&#xff1a;Google推出的一个全新的设计语言&#xff0c;它的特点就是拟物扁平化。 Material Design包含了很多内容&#xff0c;今天跟大家分享一下Material新增的动画&#xff1a; 在Android L中新增了如下几种动画&#xff1a; ? * middot;Touch feedback&…

PHP升级到4.3版本之后改变了调用存储过程的一个特性

编写者版本本文假定您熟悉 Php、Sql。郑昀掌上灵通第一稿小麻烦&#xff1a;我们按照惯例使用了一个MS Sql Server的存储过程procA&#xff0c;它给出了一个输出参数nReturn&#xff0c;而且返回了一个结果集。在如何让PHP调用这个procA的时候&#xff0c;我们遭遇了一点小麻烦…

23种设计模式之状态模式

场景 电梯的运行 维修、正常、自动关门、自动开门、向上运行、向下运行、消防状态。红绿灯 红灯、黄灯、绿灯网上购物时&#xff0c;订单的状态 下单 已付款已发货送货中已收货 核心&#xff1a;用于解决系统中复杂对象状态转换以及不同状态下行为的封装问题。 结构&…

Android ActionBar 讲解

1.Action Bar 介绍 我们能在应用中看见的actionbar一般就是下图的样子&#xff0c;比如快图应用 1.App icon 应用的图标&#xff0c;左侧带应用相当于back返回键 2.ViewControl 3.Action button 相当于普通的Button可以监听点击事件 4.Action overflow 三个点&#xff0c;相当于…