我爱编程

简单的模板引擎

2018-03-24  本文已影响0人  1w1ng

1.字符串的拼接

let songs = [
    {name: '刚刚好1',singer: '薛之谦1'},
    {name: '刚刚好2',singer: '薛之谦2'},
    {name: '刚刚好3',singer: '薛之谦3'},
    {name: '刚刚好4',singer: '薛之谦4'},
    {name: '刚刚好5',singer: '薛之谦5'}
]
let html = '<div class="ct">'
html += '<h1>热歌榜</h1><ul>'

let i
for(i = 0;i < songs.length;i++){
    html += '<li>'+ songs[i].name +' - '+ songs[i].singer +'</li>'
}
html += '</ul></div>'

document.body.innerHTML = html

2. jQuery方式 构建 DOM 对象

let songs = [
    {name: '刚刚好1',singer: '薛之谦1'},
    {name: '刚刚好2',singer: '薛之谦2'},
    {name: '刚刚好3',singer: '薛之谦3'},
    {name: '刚刚好4',singer: '薛之谦4'},
    {name: '刚刚好5',singer: '薛之谦5'}
]
let $div = $('<div class="ct"></div>')
let $ul = $('<ul></ul>')

$(songs).each((index,item) => {
    let $li = $('<li>'+ item.name +'-'+ item.singer +'</li>')
    $ul.append($li)
})

$div.append('<h1>热歌榜</h1>')
$div.append($ul)
$('body').append($div)

3. string formate

let songs = [
    {name: '刚刚好1',singer: '薛之谦1'},
    {name: '刚刚好2',singer: '薛之谦2'},
    {name: '刚刚好3',singer: '薛之谦3'},
    {name: '刚刚好4',singer: '薛之谦4'},
    {name: '刚刚好5',singer: '薛之谦5'}
]

function stringFormat (string) {
    // console.log(arguments)  // ["hi,{0}", "tian", callee: ƒ, Symbol(Symbol.iterator): ƒ]
    // 拿到arguments 除了第一项的其他项
    let parmas = [].slice.call(arguments,1)
    console.log(parmas) // ["tian", "yang"]

    // 将 string 中的 {n} 替换成 parmas{n}
    let regex = /\{(\d+)\}/g // 正则匹配 {n}
    string = string.replace(regex,function () {
        console.log(arguments)
        // 拿到 n 的下标
        let index = arguments[1]
        // 根据下标找到parmas里面的项
        return parmas[index]
    })

    return string
}


console.log(stringFormat('hi,{0} and {1}', 'tian','yang')) // 替换结果:hi,tian and yang
上一篇下一篇

猜你喜欢

热点阅读