Open TsaiChihWei opened 4 years ago
toUpperCase() 將字串轉換為大寫
let a = 'abc'
console.log(toUpperCase(a)) //'ABC'
toLowerCase() 將字串轉換為小寫
let a = 'ABC'
console.log(toLowerCase(a)) //'abc'
indexOf() 回傳字串的第一個索引值
let a = 'Today is a good day.'
console.log(a.indexOf('a')) //3
console.log(a.indexOf('z')) //-1
//如找不到字串會回傳 -1
replace(substr, newSubstr) 替換指定字串
let a = 'Apples is round, and apples is juicy.'
console.log(a.replace('is', 'are')) //'Apples are round, and apples is juicy.' 只會替換首個指定字串
console.log(a.replace(/is/g, 'are'))
//'Apples are round, and apples are juicy.' g 代表 global 全域替換,將所有指定字串都替換
/*註:
如要忽略大小寫可用 i 參數 e.g., console.log(a.replace(/apples/gi, oranges))
expected output: 'oranges are round, and oranges are juicy.'
*/
trim() 去除字串前後的空白
let a = ' hello! '
console.log(trim(a)) //'hello!'
split(separator, [limits]) 將字串拆解並回傳一個陣列
let a = 'Today!is!a!good!day.'
console.log(a.split('!')) // ["Today", "is", "a", "good", "day."]
console.log(a.split('!', 2)) // ["Today", "is"]
console.log(a.split('!', 3)) // ["Today", "is", "a"]
slice(bigin, [end]) 提取字串的某一個部分並回傳一個新字串
let a = 'hello~'
console.log(a.slice(3)) //'lo~'
console.log(a.slice(3, 5)) //'lo' 不包含 end
map(function) 原陣列的每一個元素經由回呼函式運算後所回傳一個新的陣列
let arr = [1, 2, 3]
function double (x) {
return x*2
}
console.log(arr.map(double)) // [2, 4, 6]
filter(function) 原陣列中通過回呼函式 (true) 檢驗之元素所回傳的新陣列
let arr = [1, 2, 3, 11, 12]
function isBig (x) {
return x >= 10
}
console.log(arr.filter(isBig)) // [11, 12]
// 1, 2, 3 代入 isBig function 之結果為 false 所以被 filter 掉
slice(begin, [end]) 擷取某陣列的部分並回傳一個新陣列
let arr = [1, 2, 3, 4, 5, 6]
console.log(arr.slice(1)) //[2, 3, 4, 5, 6]
console.log(arr.slice(1, 4)) //[2, 3, 4] 不包含 end
splice(start, [deleteCount], [item1], [item2].......])
//從索引 0 的位置開始,刪除 2 個元素並插入「parrot」、「anemone」和「blue」
var myFish = ['angel', 'clown', 'trumpet', 'sturgeon'];
var removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue');
// myFish 為 ["parrot", "anemone", "blue", "trumpet", "sturgeon"]
// removed 為 ["angel", "clown"]
以上範例來自 Array.prototype.splice()。
sort([compareFunction])
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]
const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// expected output: Array [1, 100000, 21, 30, 4]
//如是為了比較數字而不是字串,比較函式(compareFunction)可以僅僅利用 a 減 b。以下函式將會升冪排序陣列:
var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
return a - b;
});
console.log(numbers); // [1, 2, 3, 4, 5]
//降冪排序則用 b 減 a
numbers.sort(function(a, b) {
return b - a;
});
console.log(numbers); // [5, 4, 3, 2, 1]
以上範例來自 Array.prototype.sort()。
數字或數學相關內建函式
將字串轉為數字
Math.ceil() 無條件進位
Math.floor() 無條件捨去
Math.round() 四捨五入
Math.abs() 絕對值
Math.pow(base, exponent) 次方運算
Math.sqrt() 開根號
Math.ramdom() 隨機取數
toFixed.(digits) 取小數第幾位並四捨五入