週記JS篇(一)filter、encodeURIComponent、模板字串
阿新 • • 發佈:2019-02-13
這周在開發中使用到了遇到了filter(),之前有見過,但是沒仔細瞭解過,這次進行了學習,記住了。
1、filter():建立一個新的陣列,新陣列中的元素通過檢查指定陣列中符合條件的所有元素,而且次函式不會改變原陣列
例子:
//JS原生寫法
var age = [32, 22, 10, 40];
function checkAdult(age) {
return age>=18
}
function myFunction() {
document.getElementById("demo").innerHTML = age.filter(checkAdult);
}
//[32, 22, 40]
//ES6寫法
const data = ['spray', 'ccg', 'TAOTAO']
const result = data.filter(word => word.length>4)
console.log(result) //['spray', 'TAOTAO']
2.encodeURIComponent(str): 是對統一資源識別符號(URI)的組成部分進行編碼的方法。它使用一到四個轉義序列來表示字串中的每個字元的UTF-8編碼(只有由兩個Unicode代理區字元組成的字元才用四個轉義字元編碼)。
(1)引數str: String.URI的組成部分
(2)encodeURIComponent 轉義除了字母、數字、(、)、.、!、~、*、’、-和_之外的所有字元。
例子:
resultList[index].img = `http://10.196.51.57:8012/${encodeURIComponent(resultList[index].img)}`
注意:上面的反冒號是ES6裡面拼接字串的新方法(模板字串)
3、模板字串
(1)JS原生寫法
$('#result').append(
'There are <b>' + basket.count + '</b>' +
'items in your basket,' +
'<em>' + basket.onSale + '</em> are on sale!');
(2)ES6寫法
$('#result').append(
`There are <b>${basket.count}</b>
items in your basket,
<em>${basket.onSale}</em>`)