1. Xáo trộn mảng ngẫu nhiên
const items = ['😄', 67, true, false, '55'];
items.sort(() => Math.random() - 0.5);
console.log(items);
// [ '😄', '55', 67, false, true ]
2. Lọc chỉ giữ lại chữ số
const input = 'xieyezi 23213 is 95994 so hansome 223333';
const digits = input.replace(/[^\d]/g, '');
console.log(digits);
// 2321395994223333
3. Đảo ngược chuỗi hoặc từng từ
const text = 'xieyezi js so handsome, lol.';
const reversedText = processString(text, '');
console.log(reversedText);
// .lol ,emosdnah os sj izeyeix
const reversedWords = processString(reversedText, ' ');
console.log(reversedWords);
// izeyeix sj os ,emosdnah .lol
function processString(str, delimiter) {
return str.split(delimiter).reverse().join(delimiter);
}
4. Chuyển đổi số thập phân sang nhị phân/hexa
const value = 45;
console.log(value.toString(2)); // 101101
console.log(value.toString(16)); // 2d
5. Kết hợp nhiều đối tượng
const city = {
name: 'Chongqing',
population: '1,234,567,890'
};
const location = {
longitude: '116.4',
latitude: '39.9'
};
const merged = { ...city, ...location };
console.log(merged);
// {
// name: 'Chongqing',
// population: '1,234,567,890',
// longitude: '116.4',
// latitude: '39.9'
// }
6. Sự khác biệt giữa === và ==
// ==: Chuyển đổi kiểu (so sánh lỏng lẻo)
// ===: Không chuyển đổi kiểu (so sánh nghiêm ngặt)
console.log(0 == false); // true
console.log(0 === false); // false
console.log(1 == "1"); // true
console.log(1 === "1"); // false
console.log(null == undefined); // true
console.log(null === undefined); // false
7. Phân rã đối tượng
const forest = {
location: 'Sweden',
animals: 3,
animalsTypes: ['Lions', 'Tigers', 'Bears'],
};
const { location, animals, animalsTypes } = forest;
const [lions, tigers, bears] = animalsTypes;
console.log(location); // Sweden
console.log(animals); // 3
console.log(lions); // Lions
console.log(tigers); // Tigers
console.log(bears); // Bears
8. Hoán đổi giá trị biến
let bears = 'bears';
let tigers = 'tigers';
[bears, tigers] = [tigers, bears];
console.log(bears); // tigers
console.log(tigers); // bears
9. Kiểm tra chuỗi đặc biệt
1) Kiểm tra chuỗi đối xứng
const isMirror = (str1, str2) => {
const normalize = (str) =>
str.toLowerCase()
.normalize('NFD')
.split('')
.reverse()
.join('');
return normalize(str1) === normalize(str2);
}
console.log(isMirror('anagram', 'margana')); // true
console.log(isMirror('rac', 'car')); // true
2) Kiểm tra chuỗi hoán vị
const isPermutation = (str1, str2) => {
const normalize = (str) =>
str.toLowerCase()
.normalize('NFD')
.split('')
.sort()
.join('');
return normalize(str1) === normalize(str2);
}
console.log(isPermutation('anagram', 'nagaram')); // true
console.log(isPermutation('rat', 'car')); // false
console.log(isPermutation('heArT', 'traEH')); // true
10. Toán tử chuỗi liên kết
const player = {
name: 'xieyezi',
rating: 1000,
click: () => 'click',
pass: (teammate) => `Pass to ${teammate}`
};
console.log(player?.name); // xieyezi
console.log(player?.click?.()); // click
console.log(player?.teammate?.()); // undefined
11. Toán tử điều kiện
const oxygen = 10;
const status = oxygen < 10 ? 'Low oxygen' : 'High oxygen';
console.log(status); // High oxygen
12. Lấy phần tử ngẫu nhiên từ mảng
const elements = [24, 'You', 777, 'breaking', 99, 'full'];
const pickRandom = (arr) => arr[Math.floor(Math.random() * arr.length)];
console.log(pickRandom(elements)); // 777
13. Đóng băng đối tượng
const octopus = {
tentacles: 8,
color: 'blue'
};
Object.freeze(octopus);
octopus.tentacles = 10; // Không thay đổi
console.log(octopus); // { tentacles: 8, color: 'blue' }
14. Loại bỏ phần tử trùng lặp
const animals = ['bears', 'lions', 'tigers', 'bears', 'lions'];
const unique = (arr) => [...new Set(arr)];
console.log(unique(animals)); // [ 'bears', 'lions', 'tigers' ]
15. Làm tròn số thập phân
const number = 0.123456789;
const rounded2 = number.toFixed(2);
const rounded3 = number.toFixed(3);
console.log(rounded2); // 0.12
console.log(rounded3); // 0.123
16. Xóa toàn bộ phần tử mảng
const numbers = [1, 2, 3, 4, 5];
numbers.length = 0;
console.log(numbers); // []
17. Chuyển đổi RGB sang HEX
const rgbToHex = (r, g, b) => {
const hexify = (num) => {
const hex = num.toString(16);
return hex.length === 1 ? `0${hex}` : hex;
};
return `#${hexify(r)}${hexify(g)}${hexify(b)}`;
};
console.log(rgbToHex(46, 32, 67)); // #2e2043
18. Tìm giá trị lớn nhất/nhỏ nhất
const nums = [1, 2, 3, 4, 5, -3, 99, -45, -1];
const max = Math.max(...nums);
const min = Math.min(...nums);
console.log(max); // 99
console.log(min); // -45
19. Toán tử hợp nhất null
const nullVal = null;
const emptyStr = '';
const someNum = 13;
const a = nullVal ?? 'A default';
const b = emptyStr ?? 'B default';
const c = someNum ?? 'C default';
console.log(a); // A default
console.log(b); // ''
console.log(c); // 13
20. Lọc phần tử truthy
const values = [1, 0, undefined, null, false];
const truthy = values.filter(Boolean);
console.log(truthy); // [1]