那些你不知道的js提示

來源:互聯網
上載者:User

標籤:blog   date()   null   www.   收藏   方法   執行   多行   art   

整理了一些javascript當中一些實用的技巧,說不定可以節省很多的開發時間,趕緊收藏吧!。

  • 五分制打分系統
    /*五分制打分系統*/function getRating(rating) {    if(rating > 5 || rating < 0) throw new Error("數字不在範圍內");    return "★★★★★☆☆☆☆☆".substring(5 - rating, 10 - rating );}//調用方法及執行的結果getRating(3);//結果:★★★☆☆ 
  • 產生n個相同字元拼接成的字串
    /*產生index個相同的str字串*/function create_str(index,str) {    return new Array(index + 1).join(str);}//調用方法及執行結果create_str(2,"abc")//結果:abcabc
  • 多行字串
  • /*第一種    通過反斜線處理換行*/var str = "console.log(123)    console.log(123)    console.log(123)    console.log(123)    console.log(123)";
    /*第二種    通過函數的方式*/var str = (function () {    /**        console.log(123)        console.log(123)        console.log(123)        console.log(123)    **/}).toString().split("**")[1];
    /*第三種*/var str = "console.log(123)" +    "console.log(123)" +    "console.log(123)" +    "console.log(123)";
  • 快速產生一個,值依次遞增的數組
    Array.apply(null, new Array(15)).map(function(item, index) {  return index + 1;});//ES6文法Array.from(Array(10), (v, i) => i);
  • 劫持函數
    window.alert = function(s) {    if (confirm("是否要彈框框,內容是" + s + "?")) {        alert(s);    }};
  • 快速地將其他資料類型轉換成number類型
    console.log(typeof +"1");//numberconsole.log(typeof +new Date())//number
  • 取整同時轉成數值型
    /*直接去除小數點後面的,不能四捨五入*/("10.567890"|0)//10   number
  • 擷取隨機碼
    Math.random().toString(16).substring(2); //14位隨機碼Math.random().toString(36).substring(2); //11位隨機碼
  • 擷取數組當中的最大最小值
    Math.min.apply(Math,[1,2,3,4,5,6])//擷取最小值Math.max.apply(Math,[1,2,3,4,5,6])//擷取最小值

原文出處:https://www.meetqy.com/article?article_id=44

 

那些你不知道的js提示

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.