es6模板字符串的高級用法


一個需求:根據傳入的type顯示價格:

es5寫法

 // es5寫法
        // type    0 批發  1 零售
        let type = 0
        let pf = 16  // 批發價
        let ls = 20  // 零售價
        function getPrice(type) {
            let showText = ''
            if (type === 0) {
                showText = '你此次購買的批發價是' + pf
            } else {
                showText = '你此次購買的零售價是' + ls
            }
            return showText
        }
        console.log(getPrice(0));

es6寫法

// es6寫法
        // strings 代表固定內容 是數組
        function getPrice2(strings,type) {
           let s1 =  strings[0]
           let showText = ''
           if (type === 0) {
                showText = '批發價是' + pf
            } else {
                showText = '零售價是' + ls
            }
            return  `${s1}${showText}`
        }
        console.log(getPrice2`你此次購買的${0}`)

打印結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM