es6學習總結(二)字符串和數字操做

字符串查找

ES6還增長了字符串的查找功能,並且支持中文node

es5下的查找:indexof()git

let jspang='技術';
let blog = '很是高興你能看到這篇文章,我是你的老朋友技術。這節課咱們學習字符串模版。';
document.write(blog.indexOf(jspang));

結果:20es6

es6下的查找:include()jsp

let jspang='技術';
let blog = '很是高興你能看到這篇文章,我是你的老朋友技術。這節課咱們學習字符串模版。';
document.write(blog.includes(jspang));

結果:true學習

判斷開頭是否存在startsWith()

返回值是布爾類型es5

let jspang='技術胖';
let blog = '很是高興你能看到這篇文章,我是你的老朋友技術胖。這節課咱們學習字符串模版。';

blog.startsWith(jspang); //false

判斷結尾是否存在endsWith()

let jspang='技術胖';
    let blog = '很是高興你能看到這篇文章,我是你的老朋友技術胖。這節課咱們學習字符串模版。';

    blog.endsWidth(jspang); //false

須要注意的是:starts和ends 後邊都要加s spa

字符串的子串識別

  • includes()方法,若是在字符串中檢測到指定文本則返回true,不然返回false。
  • startsWith()方法,若是在字符串的其實部分檢測到指定文本則返回true,不然返回false。
  • endsWhit() 方法, 若是在字符串的結束部分檢測到指定文本則返回true,不然返回false。

以上三個方法均可以接受兩個參數:code

  • 第一個參數指定要搜索的文本;
  • 第二個參數是可選的,指定一個開始的搜索位置。
  • 若是指定了第二個參數,則includes方法和startsWith方法會從這個縮影值開始匹配endsWith這個方法則從這個索引值減去欲搜索文本的長度位置開始正向匹配,
  • 示例以下:
let msg = "hello world!";

//判斷
console.log(msg.includes('hello'));
//判斷結束
console.log(msg.endsWith('!'));
//判斷開始
console.log(msg.startsWith('h'));
console.log(msg.startsWith('0'));
console.log(msg.endsWith('world!'));
console.log(msg.includes('x'));

console.log(msg.startsWith('o',4));
console.log(msg.endsWith('o',8));
console.log(msg.includes('0',8));

輸出結果blog

➜  ES6練習 git:(master) ✗ node string.js
true
true
true
false
true
false

true
true
false

總結:當這3中方法都有兩個參數的時候,都起的做用是查找功能,startsWith和endsWith而不在是必定是開頭或者結尾處存在纔會是ture,startsWith這是第二參數是否是開頭,而endsWith這是第二個參數減去欲搜索文本的長度位置開始正向匹配索引

repeat() 方法

es6爲字符串提供了一個repeat方法,接受一個number類型的參數,表示該字符串的重複次數,返回值是當前字符串重複必定的次數,示例以下:

console.log('x'.repeat(2));
console.log('hello'.repeat(3));

輸出結果

xx
hellohellohello

ES6數字操做

數字判斷和轉換

數字驗證Number.isFinite( xx )

判斷是否爲數字
能夠使用Number.isFinite( )來進行數字驗證,只要是數字,不管是浮點型仍是整形都會返回true,其餘時候會返回false。

let a= 11/4;
let b=11
let c=3.1475926
console.log(Number.isFinite(b)); //true
console.log(Number.isFinite(c));//true
console.log(Number.isFinite(a));//true
console.log(Number.isFinite('jspang'));//false
console.log(Number.isFinite(NaN));//false
console.log(Number.isFinite(undefined));//false

NaN驗證

NaN是特殊的非數字,能夠使用Number.isNaN()來進行驗證。下邊的代碼控制檯返回了true。

console.log(Number.isNaN(NaN));
console.log(NaN == NaN); //false
console.log(NaN === NaN);//false
console.log(isNaN(NaN));//true

判斷是否爲整數Number.isInteger(xx)

let a=123.1;
console.log(Number.isInteger(a)); //false

整數轉換Number.parseInt(xxx)和浮點型轉換Number.parseFloat(xxx)

let a='9.18';
console.log(Number.parseInt(a));  //9
console.log(Number.parseFloat(a)); //9.18

整數取值範圍操做

相關文章
相關標籤/搜索