前端學(xué)習(xí)筆記_JS基礎(chǔ)(1)

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容