indexOf()在数组和字符串中使用的区别
相同点:
1、传参相同
var arr = [0,1,1,2,3,'4']; var str="Hello world!"; console.log("Array",arr.indexOf(1,-4)); //2 console.log("string",str.indexOf('d',-9)); //10
2、返回值类型相同
var arr = [0,1,1,2,3,'4']; var str="Hello world!"; console.log("Array",arr.indexOf(1,2)); //3 console.log("string",str.indexOf('s')); //-1
不同点:
1、字符串的indexOf在传入参数不是字符串的情况下默认会转换为字符串而数组的indexOf不会进行数据类的转换
var arr = [0,1,1,2,3,'4']; var str="Hello1 world!"; console.log("Array",arr.indexOf(1,-4)); //2 console.log("Array",arr.indexOf('4',-4)); //5 console.log("string",str.indexOf('d',-9)); //11 console.log("string",str.indexOf(1)); //5