indexOf() 数组和字符串方法

String 类型的使用

let str = 'orange';
 
str.indexOf('o'); //0
str.indexOf('n'); //3
str.indexOf('c'); //-1

Array 类型的使用

let arr = ['orange', '2016', '2016'];
 
arr.indexOf('orange'); //0
arr.indexOf('o'); //-1

Number 类型无法使用


let num = 2016;
 
num.indexOf(2); //Uncaught TypeError: num.indexOf is not a function

非要对 number 类型使用 indexOf 方法嘞?那就转换成字符串咯,接着上例来写

//二逼青年的写法
num = '2016';
num.indexOf(2); //0
 
//普通青年的写法
num.toString().indexOf(2); //0
 
//文艺青年的写法
('' + num).indexOf(2); //0
 

猜你喜欢

转载自blog.csdn.net/qq_36803558/article/details/81334879