0%

ES6-字串模板

多行字串

一般要在一串字串中插入值會這樣做

1
2
3
function sayHi(name){
console.log('Hi!' + name + '!')
}

使用backtick “`”將字串包起來,插入值用’${ value }’包起來

1
2
3
function sayHi(name){
console.log(`Hi! ${name}!`)
}

計算與三元判斷

利用字串模板的方式,也可以在模板裡進行計算,或者是做三元判斷

1
2
3
function sayHi( name, day){
console.log(`Hi! ${name}!${day*24} hour no see!`)
}
1
2
3
function sayHi( name, day){
console.log(`Hi! ${name}!${day<7}?'':'Long time no see'`)
}

多行字串

透過backtick可以直接建立多行字串

1
2
3
const letter = `Hi!Nice to meet you
My name is Ken
what is your name?`