JS的代碼是一行一行執(zhí)行的,JS中一切皆對(duì)象。
變量提升
console.log( a ); //undefined
var a = 10;
console.log( a ); //10
由此可見,a被預(yù)處理到了最前面,變量提升只對(duì)var命令聲明的變量有效,否則就會(huì)報(bào)錯(cuò)。
JS注釋
// 單行注釋
/*
* 多行注釋
*/
和文檔注釋
/**
*
* @method 求和
* @param {Number} 是一個(gè)數(shù)字
* @param {Number} 另一個(gè)數(shù)字
* @return {Number} 兩個(gè)數(shù)之和
*/
function add(a,b){
return a + b;
};
JS的數(shù)據(jù)類型
基本類型
-
String
var a = "cjj IS my Best Friend";
String常見方法
console.log( String.fromCharCode(20013,65,97) );
console.log( a.toUpperCase() );
console.log( a.toLowerCase() );
console.log( a.replace('cjj', 'cdd') );
console.log( a.substr(1,3) ); //substr(start, length)
console.log( a.substring(1,3) ); //substring(start,end-1),substring不支持負(fù)值
console.log( a.slice(1,3) ); //slice(start,end-1)
console.log( a.indexOf('m') );
console.log( a.lastIndexOf('m') );
-
Number
var b = 100; console.log( 0.1 + 0.2 ); //0.30000000000000004 浮點(diǎn)數(shù)不精確
Number類型中,NaN不等于NaN。如何判斷NaN:
if(!Number.isNaN){
Number.isNaN = function(n){
return (
typeof n === 'number' && window.isNaN(n)
);
};
};
-
Boolean
console.log( Boolean(0) ); //false -
Null
var a = null; -
Undefined
var c; console.log( c );
引用類型
-
Array
var arr = []; -
Function
function add(){}; -
Object
var obj = {};
JS中數(shù)組[] null都是Object類型。
如何判斷數(shù)據(jù)類型
console.log( typeof aaa ); //undefined
console.log( typeof "foo" ); //String
console.log( typeof 123 ); //Number
console.log( typeof true ); //Boolean
console.log( typeof { a : 1 }); //Object
console.log( typeof function(){} ); //Function
console.log( typeof null ); //Object
console.log( typeof [1,2,3] ); //Object
由此可見,typeof 并不能準(zhǔn)確判斷類型,如何解決呢?使用Object.prototype.toString