最近又在重新复习js,不怎么用有些就就生疏了,每天都要复习复习在复习才行,分享一下跟着大神学习的日常笔记记录。
有些錯誤可能是沒寫對中英字符,可能會報錯,都手寫的,見諒,废话不多说半句,开始复习吧!
Javascript的类型转换
* 通过toString()方法将数值转换成字符串
* 通过parselnt()将字符串转为整型
* 通过parseFloat()将字符串转成浮点型
* 通过'+'号将字符串转成数值
举个栗子吧:
通过toString()方法将数值转换成字符串:
var a = 3;
var b = 10;
var c = a.toString();//"3"
var d = b+c;//10+"3"=103
console.log(d);//103
通过parselnt()将字符串转为整型:
document.write(parselnt('67yellow'));//67
document.write(parselnt('yellow67'));//NaN
document.write(parselnt('53.5'));//53
document.write(parselnt('0xC'));//12(16进制里面C为12,这里会自动把16转为10)
document.write(parselnt('yellow'));//NaN
通过parseFloat()将字符串转成浮点型
document.write(parseFloat('67yellow'));//67
document.write(parseFloat('yellow67'));//NaN
document.write(parselnt('0xC'));//0(这个和整型数不一样,没办法从16转为10)
document.write(parselnt('22.5'));//22.5(字符串转为浮点数)
document.write(parselnt('22.5.22'));//22.5(后面的就会认为是一个特殊字符,所以不截取)
* 通过'+'号将字符串转成数值
var a = '3';
var b = 10;
var c = +a;//3
var d = b+c;//10+3=13
console.log(d);//13
Javascript中字符串的常用操作方法:
charAt() | 获取字符串特定索引处的字符 |
toUpperCase() | 将字符串的所有字符转成大写字母 |
indexOf() | 返回字符串中特定字符串第一次出现的位置 |
substring() | 返回字符串的某个子串 |
slice() | 返回字符串的某个子串,支持负数参数,功能更强大 |
concat() | 用于将多个字符串拼接成一个字符串 |
replace() | 将字符串中的某个子串以特定的字符串替换 |
split() | 将某个字符串分割成多个字符串,可以指定分割符 |
match() | 使用正则表达式搜索目标子字符串 |
search() | 使用正则表达式搜索目标子字符串 |
1:字符串的length属性
var a = "taoshiliu";
console.log(a.length);//9(length从1开始数)
2:字符串的charAt属性
var a = "taoshiliu";
console.log(a.charAt(2));//o(charAt从0开始数)
3:字符串的toUpperCase属性
var a = "taoshiliu";
console.log(a.toUpperCase());//TAOSHILIU
4:字符串的indexOf属性
var a = "taoshiliu";
console.log(a.indexOf('i'));//5(indexOf从0开始数)
5:字符串的lastIndexof属性
var a = "taoshiliu";
console.log(a.indexOf('i'));//5(indexOf从0开始数)
6:字符串的indexOf属性
var a = "taoshiliu";
console.log(a.indexOf('i',6));//7(indexOf从0开始数,后面添加一个要从6之后的字母开始找到i,所以为7)
7-1:字符串的substring属性
var a = "taoshiliu";
console.log(a.substring(2));//oshiliu(substring从0开始数,从o开始截取到最后)
7-2:字符串的substring属性
var a = "taoshiliu";
console.log(a.substring(2,4));//os(substring从0开始数,可以理解为4-2为截取2个值,然后从o开始截取,数2个数就是os了)
8-1:字符串的slice属性
var a = "taoshiliu";
console.log(a.slice(2));//oshiliu(slice从0开始数,从o开始截取到最后)
8-2:字符串的slice属性
var a = "taoshiliu";
console.log(a.slice(2,4));//os(slice从0开始数,可以理解为4-2为截取2个值,然后从o开始截取,数2个数就是os了)
8-3:字符串的slice属性
var a = "taoshiliu";
console.log(a.slice(2,-1));//oshili(slice从0开始数,-1为u)
8-4:字符串的slice属性
var a = "taoshiliu";
console.log(a.slice(-3,-1));//li(slice从0开始数,-1为u)
9:字符串的replace属性
var a = "taoshiliu";
console.log(a.replace(’tao‘,’morning‘));//morningshiliu
10:字符串的split属性
var a = "tao-shi-liu";
var arr = a.split("-");
for(var i = 0;i<arr.length;i++){
console.log(arr[i]);
}//依次出现三个值tao shi liu
11-1:字符串的match属性
var a = "taoshiliu";
console.log(a.match(’tao‘));//tao
11-2:字符串的match属性
var a = "taoshiliu";
console.log(a.match(’amy‘));//null
12-1:字符串的search属性
var a = "taoshiliu";
console.log(a.search(’shi‘));//3(返回为shi的索引)
12-2:字符串的search属性
var a = "taoshiliu";
console.log(a.search(’amy‘));//-1(找不到返回-1)