常用內建函式 - Number 篇
- parseInt(a) / parseInt(a, 10)
後面接的是十進位的意思
let a = 15
console.log(parseInt(a, 10)) // 15
let a = 15.56
console.log(parseInt(a)) // 15,只會解析到小數前的數字
- parseFloat(a).toFixed()
let a = 15.567
console.log(parseFloat(a).toFixed(2)) // 15.57,會自動四捨五入
console.log(parseFloat(a).toFixed()) // 15
Math.cell
無條件進位
Math. floor
無條件捨去
Math.round
四捨五入
Math.pow(2, 10)
2 的 10 次方
Math.radnom()
產生一個 0 ~ 0.99999... 的隨機數字
console.log(Math.floor(Math.radnom()*10 + 1))
// 0 ~ 0.9999...
// 0 ~ 9.9999...
// 1 ~ 10.9999...
// 利用 Math.floor 無條件捨去,就可以產生一個 1 ~ 10 的隨機數
常用內建函式 - String 篇
.toUpperCase()
轉成大寫
.toLowerCase()
轉成小寫
.charCodeAt()
取得 ASCII code
String.fromCharCode()
把 ASCII code
轉成字.indexOf()
印出索引值
.replace()
取代
let str = 'hey hello world yoyo'.replace('hey', '!!!')
console.log(str) // '!!! hello world yoyo'
let str = 'hey hello world yoyo'.replace('y', '!!!')
console.log(str) // 'he!!! hello world yoyo'
let str = 'hey hello world yoyo'.replace(/y/g, '!!!')
console.log(str) // 'he!!! hello world !!!o!!!o'
- .split()
分割
let str = 'hello world'
console.log(str.split(''))
/*[
'h', 'e', 'l', 'l',
'o', ' ', 'w', 'o',
'r', 'l', 'd'
]*/
console.log(str.split(' ')) // [ 'hello', 'world' ]
- .trim()
去掉前後空格
常用內建函式 - Array 篇
.join()
在陣列裡面加入東西,回傳字串
.map()
傳入一個函數
.filter()
傳入一個函數,ture 會留下,false 會過濾掉
.slice()
分割
let a = [0, 1, 2, 3, 4, 5 ,6]
console.log(a.slice(3)) // [3, 4, 5 ,6]
let a = [0, 1, 2, 3, 4, 5 ,6]
console.log(a.slice(3, 5)) // [3, 4]
- .splice()
插入或刪除元素
const words = ['A', 'B', 'C', 'D'];
words.splice(1, 0, 'E'); // 索引 1 處,插入 'E'
console.log(words); // ['A', 'E', 'B', 'C', 'D']
words.splice(4, 1, 'May'); // 索引 4 處,刪除 1 個元素,插入 'F'
console.log(words); // ['A', 'E', 'B', 'C', 'F']
// 'D' -> 'F'
- .sort()
排序
const array1 = [1, 30, 4, 21];
array1.sort();
console.log(array1);
// expected output: Array [1, 21, 30, 4],預設以字串方式排列
// 若是要用數字排列
var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
return a - b;
});
console.log(numbers); // [1, 2, 3, 4, 5]