ปัญหา
เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงสองสตริง str1 และ str2 เป็นอาร์กิวเมนต์แรกและอาร์กิวเมนต์ที่สองตามลำดับ
ฟังก์ชันควรนับและคืนค่าจำนวนตัวอักษรของ str1 ที่ปรากฏใน str2 เช่นกัน และหากมีการปรากฏซ้ำ เราต้องนับแยกกัน
ตัวอย่างเช่น หากอินพุตคือ
อินพุต
const str1 = 'Kk';
const str2 = 'klKKkKsl';
เอาต์พุต
const output = 5;
ตัวอย่างโค้ด
const str1 = 'Kk';
const str2 = 'klKKkKsl';
var countAppearances = (str1 = '', str2 = '') => {
const map = {};
for (let c of str1) {
map[c] = true;
}
let count = 0;
for (let c of str2) {
if (map[c]) {
count += 1;
}
}
return count;
};
console.log(countAppearances(str1, str2));
ผลลัพธ์
5