JavaScript 基礎資料型別 (Elementary Data Type) 與類型檢測

來源:互聯網
上載者:User

JavaScript 基礎資料型別 (Elementary Data Type) 與類型檢測
一、【JavaScript 基礎資料型別 (Elementary Data Type)】JavaScript 擁有動態類型。這意味著相同的變數可用作不同的類型
"string" "number" "object" "boolean" "function" "undefined"

<1> string類型
屬性:
str.length

var str = "123,ABC,900,rgy,rrrr";console.log(str.length);//20var str = "123,ABC,900,冉光宇,rrrr";console.log(str.length);//20
tip:
從實驗結果可以看出來不管是英文字元還是漢字字元,它們在length中表現一樣,
並沒有什麼區別,有幾個字元就占幾個位置,這裡並不區分多位元組字元,
在這裡它們被一視同仁


方法:

轉換大小寫:
str.toLowerCase();// 返回一個字串,該字串中的字母被轉換成小寫
str.toUpperCase();// 返回一個字串,該字串中的字母被轉換成大寫


var str = "123,ABC,900,冉光宇,rrrr";console.log(str.toLowerCase());// 123,abc,900,冉光宇,rrrrconsole.log(str.toUpperCase());// 123,ABC,900,冉光宇,RRRR


索引字元(字串):
str.charCodeAt(num);// 返回一個整數,代表指定位置字元的Unicode編碼
str.fromCharCode(num2,num2,num3);// 從一些Unicode字串中返回一個字串
str.charAt(num);// 指定索引位置處的字元,如果超出有效範圍的索引值返回Null 字元串。
str.indexOf(flag); // 返回String對象內第一次出現子字串位置
str.lastIndexOf(flag);// 返回String對象內最後一次出現子字串位置

var str = "ABC";console.log(str.charCodeAt(1));// 66 (index == 1的字元B的Unicode編碼為66)console.log(String.fromCharCode(65,66,67));// ABCconsole.log(str.charAt(5));// 空console.log(str.charAt(1));// Bvar str = "abcba";console.log(str.indexOf("b"));// 1console.log(str.lastIndexOf("b"));// 3console.log(str.indexOf("z"));// -1console.log(str.lastIndexOf("z"));// -1console.log(str.indexOf("b",2));// 3console.log(str.lastIndexOf("b",4));// 3
tip:
1.indexOf()與 lastIndexOf()若是沒有匹配到子字串,則返回-1
2.indexOf("b",2) 表示由index==2的位置開始,從左向右進行尋找
3.lastIndexOf("b",4) 表示由index==4的位置開始,從右向左進行尋找


截取字串:
str.substring(start,end);// 返回位於String對象中指定位置的子字串
str.substr(start,length);// 返回一個從指定位置開始的指定長度的子字串
str.slice(start,end);// 返回位於String對象中指定位置的子字串

var str = "0123456";var arr = str.substring(1,4);console.log(str);// 0123456console.log(arr);// 123console.log(str.substring(4,1));// 123console.log(str.substring(1));// 123456console.log(str.substring(-2));// 0123456
tip:
1.可以看出 substring(1,4)與 substring(4,1)等價,都是截取index == 1 到 index == 4 之間的字串
2.同時還可以看出它對原數組並無影響
3.參數若為負數,則返回整個完整字串

////
var str = "0123456";var arr = str.substr(1,4);console.log(str);// 0123456console.log(arr);// 1234
tip:
1.substr(1,4) 表示從index == 1的位置開始截取,向後截取4個字元
2.還可以看出它對原數組並無影響

////
var str = "0123456";var arr = str.slice(1,4);console.log(str);// 0123456console.log(arr);// 123console.log(str.slice(4,1));// 空,不支援這種方式console.log(str.slice(1));// 123456console.log(str.slice(-5));// 23456console.log(str.slice(-5,-1));// 2345
tip:
1.可以看出它對原數組並無影響
2.不支援str.slice(4,1),前面的index大於後面的index
3.支援參數為負數


Regex:
match: str.match(reg); // 返回數組
search: str.search(reg); // 返回number
replace: str.replace(reg); // 返回字串
split: str.split(reg); // 返回數組

var str = "123,ABC,900,rgy,rrrgyr";console.log(str.match(/rgy/));// ["rgy", index: 12, input: "123,ABC,900,rgy,rrrgyr"]console.log(str.match(/rgy/g));// ["rgy", "rgy"]tip: 預設匹配第一個,加了標誌"g"表示全域匹配var str = "123,ABC,900,rgy,rrrgyr";console.log(str.search(/rgy/));// 12tip: 預設匹配第一個,返回indexvar str = "123,ABC,900,rgy,rrrgyr";console.log(str.replace(/rgy/, "kkk"));// 123,ABC,900,kkk,rrrgyrconsole.log(str.replace(/rgy/g, "kkk"));// 123,ABC,900,kkk,rrkkkrconsole.log(str.replace(/(\d+),(\w+)/g, "$2,$1"));// ABC,123,rgy,900,rrrgyrvar str = "123,ABC,900,rgy,rrrgyr";var arr = str.split(",");// ["123", "ABC", "900", "rgy", "rrrgyr"]var arr = str.split(/,/);// ["123", "ABC", "900", "rgy", "rrrgyr"]tip: split()方法中參數可以為Regex,也可以為其他字串

<2> number類型
Number.MAX_VALUE // 1.7976931348623157e+308
Number.MIN_VALUE // 5e-324


Number.NEGATIVE_INFINITY // Infinity(無窮大)
Number.POSITIVE_INFINITY // -Infinity(負無窮大)


number轉換成string:
console.log(Math.ceil("1000.3"));// 1001(向上取整)console.log(Math.floor("1000.3"));// 1000 (向下取整)console.log(Math.round("1000.3"));// 1000(四捨五入)console.log(parseInt("1000.3"));// 1000console.log(parseFloat("1000.3"));// 1000.3


parseInt()和 parseFloat():

parseInt(str [, radix]);
parseFloat(str [, radix]);

返回的數都為10進位

radix為可選項,表示進位,該值介於 2 ~ 36 之間,表示以什麼進位來進行解析
當參數radix的值為0,或沒有設定該參數時,parseInt()會根據string來判斷數位基數。

console.log(parseInt("1011", 2)); // 11console.log(parseInt("18", 10));// 18

parseFloat()用法類似


<3> object類型

屬性:
constructor
prototype


方法:
hasOwnProperty(); //用來判斷,一個屬性是不是區域屬性
isPrototypeOf();//用來判斷,某個prototype對象和某個執行個體之間的關係。
toString();
toLocaleString();
valueOf();

function Cat(name,color){this.name = name;this.color = color;}Cat.prototype.type = "貓科動物";Cat.prototype.eat = function(){alert("吃老鼠");}var cat1 = new Cat("大毛","黃色");var cat2 = new Cat("二毛","黑色");alert(Cat.prototype.isPrototypeOf(cat1));//truealert(Cat.prototype.isPrototypeOf(cat2));//truealert(cat1.hasOwnProperty("name"));//truealert(cat1.hasOwnProperty("type"));//false

<4> boolean類型
boolean的隱式轉換規則:

1.特殊值undefined和null變成false
2.數字0和NaN變成false
3.Null 字元串變成false
4.所有其他值都變成true


<5> function類型在js中定義函數的方式有兩種:一種是函式宣告,另一種是函數運算式


函式宣告:
function functionName(arg0, arg1, arg2) {}


函數運算式:
var functionName = function(arg0, arg1, arg2){};


tip:
函式宣告時,它有一個重要的特性就是函式宣告提升,在執行代碼之前會先讀取函式宣告
因此,可以把函式宣告放在調用它的語句後面。
例如:
say();function say(){alert("hello world!");}

JS中沒有函數重載的概念,函數調用的時候,會以就近原則來調用


<6> undefined類型
undefined與null的關係:


console.log(undefined == null);// true
console.log(undefined === null);// false


瞭解更多undefined與null:
http://www.ruanyifeng.com/blog/2014/03/undefined-vs-null.html


判斷undefined類型:
if (typeof(value) == "undefined") {
alert("undefined");
}


//////////////////////
二、【資料類型檢測】
引子:

 

var nums = [1,2,3,4];typeof nums // objectnums.constructor === Array;// truenums instanceof Array;// trueObject.prototype.toString.call(nums);// "[object Array]"

 


/////////////////////
<1> typeof

文法:
typeof value;
//支援6個值
"string" "number" "object" "boolean" "function" "undefined"


例子:
console.log(typeof "123");// "string"console.log(typeof 123);// "number"console.log(typeof {});// "object"console.log(typeof []);// "object"console.log(typeof null);// "object"console.log(typeof true);// "boolean"console.log(typeof function(){});// "function"console.log(typeof undefined);// "undefined"


/////////////////////
<2> instanceof
文法:
value instanceof ?;


例子:
var obj = {name : "kylin",age : 21,list : [1,2,3]}var Person = function(name,age){this.name = name;this.age = age; }var p = new Person("kylin", 21);console.log(p instanceof Person); //trueconsole.log(obj instanceof Person); //falseconsole.log(obj instanceof Object); //trueconsole.log(new Date() instanceof Date); //trueconsole.log([] instanceof Array); //true

/////////////////////
<3> constructor

文法:
value.constructor === ?;


例子:
var Person = function(name,age){this.name = name;this.age = age; }var p = new Person("kylin", 21);console.log(p.constructor == Person); //trueconsole.log([].constructor == Array); //trueconsole.log(new Date().constructor == Date)//true

/////////////////////
<4> Object.prototype.toString.call()
文法:
Object.prototype.toString.call(value);

例子:
Object.prototype.toString.call("123");// "[object String]"Object.prototype.toString.call(123);// "[object Number]"Object.prototype.toString.call({});// "[object Object]"Object.prototype.toString.call([]);// "[object Array]"Object.prototype.toString.call(null);// "[object Null]"Object.prototype.toString.call(true);// "[object Boolean]"Object.prototype.toString.call(function(){});// "[object Function]"Object.prototype.toString.call(undefined);// "[object Undefined]"



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.