JS中神奇的String.indexOf()

在JavaScript中,String.indexOf(searchvalue) 方法可返回某个指定的字符串值在字符串中首次出现的位置。这是个常见的方法,但却有着不常见的用法。

常用的用法:

'this is jimson'.indexOf('this'); //return 0;
'this is jimson'.indexOf('is');   //return 2;
'this is jimson'.indexOf('jimson'); //return 8;
'this is jimson'.indexOf('that'); //return -1; 

如果能找到,则返回该字符串首次出现的位置的索引(从0 开始), -1 则表示没有找到。

高级的用法(使用fromindex):

'this is jimson'.indexOf('this', 4); //return -1;
'this is jimson'.indexOf('is', 4);   //return 5;
'this is jimson'.indexOf('jimson', 4); //return 8;

根据方法签名: stringObject.indexOf(searchvalue,fromindex), indexOf 提供了第二个参数 fromindex来表明从哪个位置开始查找。所以上面例子中从第四位开始查找this则找不到,查找is则找到第二个is出现的地方。 返回的index 结果则不受fromindex 的影响。

神奇的用法一(searchvalue 为空):

'this is jimson'.indexOf(''); //return 0; 
'this is jimson'.indexOf('', 4); //return 4; 
'this is jimson'.indexOf('', 10); //return 10; 
'this is jimson'.indexOf('', 14); //return 14; 
'this is jimson'.indexOf('', 15); //return 14; 
'this is jimson'.indexOf('', 100); //return 14; 
'this is jimson'.indexOf(''0); //return 0; 
'this is jimson'.indexOf(''-1); //return 0; 

searchvalue为空的情况下,如果fromIndex 小于stringObject的长度时,则返回fromIndex,如果fromIndex大于stringObject的长度时,则返回stringObject的长度, 当fromIndex小于或等于0时,则返回0.

神奇的用法二(searchvalue 为非string):

'test123'.indexOf(123); //return 4;
'test18'.indexOf(0x12); //return 4;
'testtrue'.indexOf(true); //return 4;
'testundefined'.indexOf(); //return 4;
'testnull'.indexOf(null); //return 4;

Javascript 无类型语言,所以searchvalue可以赋值各种类型。通过测试发现,当searchvalue不是string 类型时,则会把searchvalue转换为string类型,在进行查找。 那么是如何转换的呢? 首先猜测调用toString(),但是碰到undefined并没有toString(),所以测试是调用searchvalue + ''的方式转换:

123 + ''; //return '123';
0x12 + ''; //return '18';
true + ''; //return 'true';
undefined + ''; //return 'undefined';
null + ''; //return 'null';

神奇的用法三(searchvalue 为数组):

'this is jimson'.indexOf([]); //return 0;
'this is jimson'.indexOf([],4); //return 4;
'this is jimson'.indexOf(['']); //return 0;
'this is jimson'.indexOf(['this']); //return 0;
'this is jimson'.indexOf(['is'], 4); //return 5;
'this is jimson'.indexOf(['this', 'is']); //return -1; 
'this,is jimson'.indexOf(['this', 'is']); //return 0; 
'this,is jimson,12'.indexOf(['jimson', 12]); //return 8;

这种用法其实是searchvalue 为非string的扩展,究其原因也可以用searchvalue + ''转换方式解释。

扩展 String.includes():

既然indexOf 有着这么神奇的用法,那么基于indexOf实现的其他函数有没有这么神奇的用法呢?
看下stringObject.includes(searchvalue, fromindex):

'testundefined'.includes(); //return true;
'test18'.includes(0x12); // return true;
'this,is jimson,12'.includes(['jimson', 12]); //return true;

参考文档:
String.prototype.includes() - JavaScript | MDN
https://tc39.es/ecma262/#sec-string.prototype.includes

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值