An warware: maimaita ƙamus ts

Yin maimaitawa akan ƙamus a cikin TypeScript, babban nau'in JavaScript mai ƙarfi, na iya zama dabara mai amfani wajen sarrafa bayanai ko warware batutuwan shirye-shirye. Tare da TypeScript, zamu iya ƙirƙirar nau'ikan hadaddun, wanda zai haifar da ƙarin haske, ƙarin lambar bayanin kai. A cikin wannan labarin, za mu saba da dabarun maimaitawa ta hanyar ƙamus a cikin TypeScript kuma mu bayyana lambar a matakai don kyakkyawar fahimta.

Tsayawa kan ra'ayi, ƙamus a cikin TypeScript abu ne da ke riƙe nau'i-nau'i masu ƙima. Kuna iya amfani da ƙamus na TypeScript don adanawa da dawo da ƙima bisa maɓallan su, waɗanda zasu iya zama masu amfani don sarrafa bayanai da warware matsala. Yanzu bari mu ƙara zurfafa bincike kan tsarin maimaita ƙamus.

 
let dictionary = {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
};

for (let key in dictionary) {
    if (dictionary.hasOwnProperty(key)) {
         let value = dictionary[key];
         console.log(key, value);
    }
}

Wannan lambar tana aiki ta farko ta ayyana ƙamus abu mai maɓalli-darajar nau'i-nau'i uku. Sannan yana amfani da madauki don maimaita akan waɗannan nau'ikan. Ana amfani da aikin 'hasOwnProperty' don tabbatar da cewa kawai kaddarorin abin da kansa ya haɗa, ba kadarorin da aka gada daga sarkar samfurin ba.

Yin aiki tare da ɗakunan karatu na TypeScript kuma ayyuka don irin waɗannan dalilai suna da albarkatu.

Hanyar maɓalli

Za mu iya amfani da hanyar Object.keys don samun jeri na maɓalli, sa'an nan kuma amfani da madauki don maimaita kan wannan jeri.

 
Object.keys(dictionary).forEach(key => {
    let value = dictionary[key];
    console.log(key, value);
});

A cikin wannan snippet, ana amfani da hanyar Object.keys() don samun tarin kaddarori masu yawa. An gabatar da wannan hanyar a cikin ES5 kuma ana samun goyan bayan duk masu bincike na zamani. Yana dawo da jerin sunayen abubuwan da aka ba da sunaye masu yawa.

Amfani da Shigarwa da ForEach

Shigarwa wata hanya ce don samun tsararru tare da tsararru a ciki. Kowane ɗayan waɗannan tsararrun ciki yana da abu biyu: maɓalli da ƙima.

 
Object.entries(dictionary).forEach(([key, value]) => {
    console.log(key, value);
});

Wannan yana amfani da hanyar shigarwa don samun jeri na maɓallai da ƙimar abu bi-biyu, wanda za'a ƙirƙira su tare da madaidaicin madaidaicin inda kowane maɓalli-darajar biyu ke rarrabuwa zuwa mabambanta biyu, maɓalli da ƙima.

Yin aiki tare da abubuwan ƙamus da maimaitawa ta abubuwan da aka haɗa guda biyu matsala ce ta gama gari a ciki Shirye-shiryen Rubutun rubutu. Ta hanyar amfani da ginanniyar ayyuka da tushen tushen harshe, ya zama mafi sauƙi. Ka tuna, koyaushe game da amfani da kayan aikin da ya dace don aikin.

Shafi posts:

Leave a Comment