JavaScript - 內建物件
目錄
一、Number
Number 物件是原始數值的包裝物件。
Number 建立方式 new Number()。
1、常用數字
//整數:10 console.log(10); //小數:3.14 console.log(3.14); //科學計數法:1e5 | 1e-5 console.log(1e5); console.log(1e-5); //正負無窮:Infinity | -Infinity console.log(Infinity); console.log(-5/0);
2、常用進位制
//二進位制:0b1010 var a = 0b1010; // 8421 //八進位制:0o12 var b = 012; //十進位制:10 var c = 10; //十六進位制:0xA var d = 0xA; console.log(a, b, c, d);
3、NaN
NaN 屬性是代表非數字值的特殊值。該屬性用於指示某個值不是數字。
可以把 Number 物件設定為該值,來指示其不是數字值。
提示: 請使用 isNaN() 全域性函式來判斷一個值是否是 NaN 值。
4、常用常量
//最大值:MAX_VALUE(1.7976931348623157e+308) console.log(Number.MAX_VALUE); // >>>1.7976931348623157e+308 //最小值:MIN_VALUE(5e-324) console.log(Number.MIN_VALUE); // >>>5e-324 //正負無窮:NEGATIVE_INFINITY | POSITIVE_INFINITY(Infinity | -Infinity) console.log(Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY); // >>> -Infinity Infinity //超界數及其運算存在不精準 console.log(999999999999998); console.log(9999999999999989); // 9999999999999988 console.log(3.1 + 3.2); // 6.300000000000001 //可以用,分割來顯示兩個數 console.log(3.1, 3.2);
5、例項方法
- toExponential(n) :把物件的值轉換為指數計數法。
- toFixed(n):把數字轉換為字串,結果的小數點後有指定位數的數字。
- toPrecision(n):把數字格式化為指定的長度。
- toString():把數字轉換為字串,使用指定的進位制。
.toString(2),.toString(6),.toString(8),.toString(16) ,預設:.toString(10)
注意:常數的轉換進位制必須為 10..toString(),即中間存在兩個點- valueOf():返回一個 Number 物件的基本數字值。
注意:bug數字13.145符合五舍六入。
//toExponential(n) //3.14.toExponential(1) => 1.3e+1 (先科學記數,再確定精度,n為小數精度) console.log(13.145.toExponential(3)); // 13.14 => 1.314e+1 => 1.31e+1 (13.15=>1.32e+1) 通常為四捨五入 //toFixed(n) //3.14.toFixed(1) => 3.1 (先確定精度,再普通記數,n為小數精度) console.log(3.14.toFixed(1)) // 3.14四捨五入保留一位小數 //toPrecision(n) //13.14.toPrecision(1|2) => 1e+1|13 (先確定精度,再記數,n為位數進度) console.log(13.14.toPrecision(1)) // 1e+1 console.log(13.14.toPrecision(2)) // 13 console.log(13.14.toPrecision(3)) // 13.1 console.log(156.14.toPrecision(1)) // 2e+2 //toString() var num = 10; console.log(num.toString()); //10 console.log(10..toString(8)); //12
二、Data時間
1、建立時間物件
- new Date(); :最常用
- new Date(milliseconds);: 給予自定時間戳,毫秒單位
- new Date(dateString);:給予自定時間
- new Date(year, month, day, hours, minutes, seconds, milliseconds);
引數說明:
year的值為:想設定的年份-1900。
例如:需設定的年份是1997則year的值應為97。所以Date中可設定的年份最小為1900;month:值域為0~11,0代表1月,11表代表12月;
date:值域在1~31之間;
hours:值域在0~23之間。
從午夜到次日凌晨1點間hrs=0,從中午到下午1點間hrs=12;min和sec:值域在0~59之間。
例 Date day=new Date(11,3,4); 》》 day中的時間為:04-Apr-11 12:00:00 AM
另:bug時間 1910年2月30日,它將被解釋成3月2日。
Date day=new Date(10,1,30,10,12,34);var d = new Date(); //最常用 // >>>Date 2018-10-17T11:02:09.556Z // var d1 = new Date(milliseconds); 給予自定時間戳,毫秒單位 var d1 = new Date(11111111); // var d2 = new Date(dateString); 給予自定時間 var d2 = new Date("2018/1/1"); var d2 = new Date(2018,1,1"); // var d3 = new Date(year, month, day, hours, minutes, seconds, milliseconds); var d3 = new Date(118,9,17,19,27,34);
2、Date 物件屬性
屬性 描述 constructor 返回對建立此物件的 Date 函式的引用。 prototype 使您有能力向物件新增屬性和方法。
3、常用方法
- date.getFullYear() :從 Date 物件以四位數字返回年份。例:2018
- date.getMonth() + 1:從 Date 物件返回月份 (0 ~ 11)。獲取準確月份必須+1
- date.getDate():從 Date 物件返回一個月中的某一天 (1 ~ 31)。
- date.getDay():從 Date 物件返回一週中的某一天 (0 ~ 6)。0-週日
- date.getHours() :返回 Date 物件的小時 (0 ~ 23)。
- date.getMinutes() :返回 Date 物件的分鐘 (0 ~ 59)
- date.getSeconds() :返回 Date 物件的秒數 (0 ~ 59)
- date.getMilliseconds():返回 Date 物件的毫秒(0 ~ 999)
- date.getTime():返回 1970 年 1 月 1 日至今的毫秒數。即,時間戳
- 其餘物件方法查詢
4、常見格式時間
- getUTCFullYear():根據世界時從 Date 物件返回四位數的年份。
- getUTCDate():根據世界時從 Date 物件返回月中的一天 (1 ~ 31)。
- getUTCHours():根據世界時返回 Date 物件的小時 (0 ~ 23)。
- ……
三、String字串
1、常見字串
'string' | "string" | 'my name is "zero"' | "I'm boy" | "I \"love\" you"2、字串屬性
屬性 描述 constructor 對建立該物件的函式的引用 length 字串的長度(常用) prototype 允許您向物件新增屬性和方法
3、常用方法
- chartAt(n):返回在指定索引位置的字元。同[n]
- concat(str):連線兩個或更多字串,並返回新的字串。
- indexOf(str):返回查詢的字串值在字串中首次出現的位置。
- lastIndexOf(str):從後向前搜尋字串,並從起始位置(0)開始計算返回字串最後出現的位置。
- replace(re, str):在字串中查詢匹配的子串, 並替換與正則表示式匹配的子串。
- substr(n, m):從起始索引號(n)提取字串中指定數目(m)的字元。
- substring(n, m):提取字串中兩個指定的索引號之間(n,m)的字元。(m省略代表擷取到最後)
- slice(n, m):提取字串的片斷,並在新的字串中返回被提取的部分。同substring(n, m)
- split(re):以指定正則(re)將字串拆分為陣列
- toUpperCase():轉換為大寫
- toLowerCase():轉換為小寫 trim():去除首尾空白字元
- 其餘方法查詢
// '' | "" | "''" | '""' | "\"\"" | '\'\'' var str = '字串'; console.log(str); // >>字串 // length console.log(str.length); //>>> 3 // 方法 str = "abc123hello123GOOD123嘿嘿"; // 自定索引下的字元 console.log(str.charAt(1)); //>>> b console.log(str[1]);//>>> b // 拼接,返回拼接後的字串 var newStr = str.concat(123); console.log(str,'\n', newStr); //>>>abc123hello123GOOD123嘿嘿 abc123hello123GOOD123嘿嘿123 // indexOf(str):指定字串第一次出現的位置 console.log(str.indexOf("123")); // 3 // replace(re, str):將正則匹配到的字串替換為指定字串 newStr = str.replace("hello", "world"); console.log(str, newStr); //>>>abc123hello123GOOD123嘿嘿 abc123world123GOOD123嘿嘿 // substr(n, m):從索引n開始,擷取m個字元長度(m省略代表擷取到最後) // 索引3開始,擷取3個字元長度 newStr = str.substr(3, 3); console.log(newStr); //>>>123 // slice(n, m):同substring(n, m) // 索引3開始,6結束(不包含6) [3, 6) newStr = str.slice(3, 6); console.log(newStr); //>>>123 // split(re, n):以指定正則將字串拆分為陣列, n可選為擷取後得到的陣列最大長度 var arr = str.split("123", 2); console.log(arr); //>>Array [ "abc", "hello" ] // trim():去除首尾空白字元 str = " 123 abc " console.log(str.trim()); //>>>123 abc
四、Array陣列
1、陣列物件
var cars = ["Saab", "Volvo", "BMW"];
2、常用屬性
屬性 描述 constructor 返回建立陣列物件的原型函式。 length 設定或返回陣列元素的個數。 prototype 允許你向陣列物件新增屬性或方法。 3、常用方法
- concat(array2,array3,...,arrayX):連線兩個或更多的陣列,並返回結果。
- indexOf(ele):指定元素第一次出現的位置
- lastIndexOf(ele):指定元素最一次出現的位置 ,在一個字串中的指定位置從後向前搜尋。
- reverse():反轉陣列的元素順序。
- includes(ele, n):從索引n開始往後,元素ele是否在陣列中,做全等匹配,索引從頭開始n可以省略(in只做值匹配)
- fill(ele):以指定元素填充整個陣列
- slice(n, m):從索引n開始,擷取到索引m(m省略代表擷取到最後)
- join(str):以指定字串連線成字串
- 查詢其他方法
// 陣列的定義與取值,索引從0開始 var arr = [1, 2, 3]; console.log(arr); console.log(arr[1]); //Array(3) [ 1, 2, 3 ] //2 arr = ['1', '2', '3']; console.log(arr); //Array(3) [ "1", "2", "3" ] arr = ["1", true, [{key: "value"}]] console.log(arr); console.log(arr[2][0].key); //Array(3) [ (1) […], true, "1" ] //value // length console.log(arr.length); // 3 // 常用方法 // concat(arr):將目標陣列拼接到指定陣列之後 console.log([1, 2, 3].concat(["4", "5", "6"])); // 結果是新陣列 Array(6) [ 1, 2, 3, "4", "5", "6" ] // indexOf(ele):指定元素第一次出現的位置 // lastIndexOf(ele):指定元素最一次出現的位置 console.log(arr.indexOf(true)); // 1 // reverse():反轉陣列 console.log(arr.reverse()); // 反轉的到新陣列 Array(3) [ (1) […], true, "1" ] // includes(ele, n) arr = [1, "1", "2"]; console.log(1 in arr); //true console.log(arr.includes(1, 1)); //false // 只匹配數字1,從索引1開始 // fill(ele):以指定元素填充整個陣列 arr.fill(null); console.log(arr); // Array(3) [ null, null, null ] // 操作原陣列,一般用來清空陣列中的資料(不操作長度) // slice(n, m):從索引n開始,擷取到索引m(m省略代表擷取到最後) arr = [1, 2, 3, 4, 5]; console.log(arr.slice(1, 3)); // 索引[1, 3) >> Array [ 2, 3 ] // join(str):以指定字串連線成字串 var str = arr.join("@"); console.log(str); // [email protected]@[email protected]@5
4、增刪改方法
- push(ele):從尾加 ; unshift(ele):從頭加
- pop():從尾刪 ; shift():從頭刪
- splice(begin, length, ...eles):完成增刪改
begin開始索引, length長度, 新元素們(可以省略)// 增刪改操作方法: 操作的都是原陣列 // push() 尾加 | unshift() 頭加 // pop() 尾刪 | shift() 頭刪 arr.push(6) console.log(arr); arr.unshift(0); console.log(arr); // 一次操作一個元素 arr.pop(); arr.shift(); console.log(arr); // splice方法 // begin開始索引 // length長度 // 新元素們(可以省略) // 1, 2, 3, 4, 5 // 從頭加 arr.splice(0, 0, 0); // 從索引0前方開始操作,操作原陣列0個長度,結果多了個元素0 console.log(arr); // 0, 1, 2, 3, 4, 5 // 從尾加 arr.splice(arr.length, 0, 6); console.log(arr); // 0, 1, 2, 3, 4, 5, 6 // 從頭刪 arr.splice(0, 1) // 從索引0開始,操作原陣列一位,替換的新值省略代表刪除 console.log(arr); // 1, 2, 3, 4, 5, 6 // 從尾刪 arr.splice(arr.length - 1, 1) console.log(arr); // 1, 2, 3, 4, 5 // 替換 arr.splice(2, 1, "3", [0, 0], "3"); // 從索引2開始,用"3", [0, 0], "3"替換掉1位 console.log(arr); // 1, 2, "3", [0, 0], "3", 4, 5
5、回撥函式方法
- filter(function(value, index){ return true | false}):過濾器
- every(function(value, index){ return 條件表示式; }):全部滿足條件
- some(function(value, index){ return 條件表示式; }):部分滿足條件
- reduce(function(prev,value,index){ return prev * value; }):累積
- sort(function(o, n){ return o > n }):正逆向排序
- 面對物件簡單回撥
// 做網路請求的物件 var web = { // 初始化接受的資料屬性 receive: null, // 請求資料方法 send: function () { console.log("開始請求資料..."); // 利用時間戳實現等待一秒 var b_time = new Date().getTime(); // 開始計數 var e_time = new Date().getTime(); // 結束計數 while(e_time - b_time < 1000) { // console.log(11); e_time = new Date().getTime(); //迴圈判斷,更新結束的計數 } //模擬獲取的資料 var data = [1, 2, 3, 4, 5]; console.log("資料請求完畢..."); // 回撥 如果獲取receive的資料,並且獲取請求的資料 if (web.receive && data) { web.receive(data); } } } // web.send(); // console.log(new Date().getTime()); // 如果獲取資料後的操作 //用於內部的receive回撥,此時receive不為空 web.receive = function(data) { console.log(data); } // 可以請求資料了 web.send();
- filter 指定過濾
filter() 方法建立一個新的陣列,新陣列中的元素是通過檢查指定陣列中符合條件的所有元素。
注意: filter() 不會對空陣列進行檢測。
注意: filter() 不會改變原始陣列。
// 過濾器回撥函式的執行次數 = 被過濾陣列的元素個數 // 需要回調的函式 var arr = [4, 6, 2, 1, 5, 3]; var getResult = function (v, i) { if (v < 5) { return true; } } var newArr = arr.filter(getResult); // 返回值: true | false console.log(arr); //Array(4) [ 4, 2, 1, 3 ] console.log(newArr); //false
- every 全部滿足 some 部分滿足
// 全部滿足: every // 引數: 值, 索引, 所屬陣列 // true:所有元素都滿足條件 // false:有一個不滿足條件即可 var arr = [4, 6, 2, 1, 5, 3]; var res = arr.every(function(v) { return v > 3; }); console.log(res); // false // 過濾器返回值: true | false // 部分滿足: some // true:有一個滿足條件即可 // false:所有元素都不滿足條件 res = arr.some(function(v) { return v > 3; }); console.log(res); //true
- reduce 累乘
// 累積: reduce var arr = [4, 6, 2, 1, 5, 3]; arr = [4, 2, 1, 3, 5]; res = arr.reduce(function(prev,value,index){ return prev * value; }) console.log(res); // 4*2*1*3*5
- sort 排序
// 排序 var arr = [4, 6, 2, 1, 5, 3]; newArr = arr.sort(function(o, n) { // return o > n; // 升序, 沒有回撥函式 return o < n; // 降序 }) console.log(newArr); //Array(5) [ 5, 4, 3, 2, 1 ]
五、Math
Math 物件用於執行數學任務。
Math 物件並不像 Date 和 String 那樣是物件的類,因此沒有建構函式 Math()。
1、常用常量
- E:返回算術常量 e,即自然對數的底數(約等於2.718)
- LN2:返回 2 的自然對數(約等於0.693)
- LN10:返回 10 的自然對數(約等於2.302)
- LOG2E:返回以 2 為底的 e 的對數(約等於 1.4426950408889634)
- LOG10E:返回以 10 為底的 e 的對數(約等於0.434)
- PI:返回圓周率(約等於3.14159)
- SQRT1_2:返回 2 的平方根的倒數(約等於 0.707)。
- SQRT2:返回 2 的平方根(約等於 1.414)。
2、常用方法
- abs(x):返回 x 的絕對值
- ceil(x):向上取整
- floor(x):向下取整
- max(...n):求最大值
- min(...n):求最小值
- pow(x,y):返回 x 的 y 次冪
- random():返回 0 ~ 1 之間的隨機數
- round(x):四捨五入
- 查詢其他方法
console.log(Math.abs(-10)); // 絕對值 console.log(Math.floor(3.9)); // 向下取整 console.log(Math.max(3, 5, 7, 1, 9.5)) // 取大值 // 隨機數: [0, 1) console.log(Math.random()); // [0, 5) // Math.random() * 5; // [0, 5]整數 // Math.floor(Math.random() * 6); // [0, 6) => 向下取整 => [0, 5] // parseInt(Math.random() * 6); // [0, 6) => 取整數部分 => [0, 5] // [5, 10] ==>> [0, 5]整數 + 5 // parseInt(Math.random() * 6) + 5 // [min, max] // parseInt(Math.random() * (max - min + 1)) + min
- 封裝函式實現指定範圍內的隨機數
//封裝獲取指定範圍的隨機數 function randomNum(min, max) { return parseInt(Math.random() * (max - min + 1)) + min; } for (var i = 0; i < 20; i++) { console.log(randomNum(5, 8)); }
六、正則
正則表示式是描述字元模式的物件。
正則表示式用於對字串模式匹配及檢索替換,是對字串執行模式匹配的強大工具。
1、語法
var patt=new RegExp(pattern,modifiers); //或者更簡單的方式: var patt=/pattern/modifiers; // 建構函式 var re = new RegExp('^\\w', 'igm'); // 字面量 var re = /^\w/igm;
- pattern(模式):描述了表示式的模式
- modifiers(修飾符): 用於指定全域性匹配、區分大小寫的匹配和多行匹配
注意:當使用建構函式創造正則物件時,需要常規的字元轉義規則(在前面加反斜槓 \)。
//比如,以下是等價的: var re = new RegExp("\\w+"); var re = /\w+/;
2、修飾符
- i:不區分大小寫進行匹配
- g:全文匹配 (查詢所有匹配而非在找到第一個匹配後停止)。
- m:多行匹配
3、正則方法
方法 描述 exec() 檢索字串中指定的值。返回找到的值,並確定為第一條結果所有資訊的陣列。 test() 檢索字串中指定的值。返回 true 或 false。 toString() 返回正則表示式的字串。 4、字串方法
方法 描述 search(re) 檢索與正則表示式相匹配的值,返回匹配的索引,查詢失敗返回-1 match(re) 找到一個或多個正則表示式的匹配,返回陣列(可全文匹配) replace(re, newStr) 替換與正則表示式匹配的子串(可全文匹配) split(re, n) 把字串分割為字串陣列,n的值可以決定結果的陣列長度(可選引數) // 建構函式 var re = new RegExp('\\w'); var res = re.test("abc"); console.log(res); //true // 字面量 re = /\w/; res = re.test("abc"); console.log(res); //true res = re.exec("abc"); console.log(res); //Array [ "a" ] // 字串的match方法 str = "ABCABC"; // re = /a/; // null => test // re = /a/i; // 非多文匹配類似於exec re = /a/ig; // 所有滿足結構的結果陣列 var arr = str.match(re); console.log(arr); //Array [ "A", "A" ] str = "abc123x9y8z7\n123"; re = /^\d/m; arr = str.match(re); console.log(arr); //Array [ "1" ] // 修飾符 // i: 不區分大小寫 // g: 全文匹配(多匹配) // m: 多行匹配