ปัญหา
เราจำเป็นต้องเขียนฟังก์ชัน 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