जावास्क्रिप्ट forEach ()

इस ट्यूटोरियल में, आप उदाहरणों की मदद से JavaScript forEach () विधि के बारे में जानेंगे।

forEach()विधि एक समारोह कॉल करता है और एक सरणी के तत्वों से अधिक iterates। forEach()विधि को भी मैप्स और सेट पर इस्तेमाल किया जा सकता है।

जावास्क्रिप्ट forEach

forEach()विधि का सिंटैक्स है:

 array.forEach(function(currentValue, index, arr))

यहाँ,

  • function (currentValue, index, arr) - एक एरे के प्रत्येक तत्व के लिए चलाया जाने वाला फंक्शन
  • currentValue - एक सरणी का मान
  • सूचकांक (वैकल्पिक) - वर्तमान तत्व का सूचकांक

गिरफ्तार (वैकल्पिक) - वर्तमान तत्वों की सरणी

Arrays के साथ आगे बढ़ें

forEach()विधि एक सरणी से पुनरावृति किया जाता है। उदाहरण के लिए,

 let students = ('John', 'Sara', 'Jack'); // using forEach students.forEach(myFunction); function myFunction(item) ( console.log(item); )

आउटपुट

 जॉन सारा जैक

उपरोक्त कार्यक्रम में, forEach()विधि myFunction()एक छात्र सरणी के प्रत्येक तत्व को प्रदर्शित करने वाले फ़ंक्शन को लेती है ।

ऐरे तत्वों को अद्यतन करना

जैसा कि हमने उपरोक्त उदाहरण में देखा है, forEach()सरणी के ऊपर पुनरावृति करने के लिए विधि का उपयोग किया जाता है, यह सरणी तत्वों को अपडेट करने के लिए काफी सरल है। उदाहरण के लिए,

 let students = ('John', 'Sara', 'Jack'); // using forEach students.forEach(myFunction); function myFunction(item, index, arr) ( // adding strings to the array elements arr(index) = 'Hello ' + item; ) console.log(students);

आउटपुट

 ("हैलो जॉन", "हैलो सारा", "हैलो जैक")

तीर समारोह के साथ forEach

आप forEach()प्रोग्राम लिखने की विधि के साथ एरो फ़ंक्शन का उपयोग कर सकते हैं । उदाहरण के लिए,

 // with arrow function and callback const students = ('John', 'Sara', 'Jack'); students.forEach(element => ( console.log(element); ));

आउटपुट

 जॉन सारा जैक

पाश के लिए forEach ()

यहाँ एक उदाहरण है कि हम forलूप के साथ और साथ एक प्रोग्राम कैसे लिख सकते हैं forEach()

लूप के लिए उपयोग करना

 const arrayItems = ('item1', 'item2', 'item3'); const copyItems = (); // using for loop for (let i = 0; i < arrayItems.length; i++) ( copyItems.push(arrayItems(i)); ) console.log(copyItems);

आउटपुट

 ("आइटम 1", "आइटम 2", "आइटम 3")

ForEach का उपयोग करना ()

 const arrayItems = ('item1', 'item2', 'item3'); const copyItems = (); // using forEach arrayItems.forEach(function(item)( copyItems.push(item); )) console.log(copyItems);

सेट्स के साथ … के लिए

आप forEach()विधि का उपयोग करके सेट तत्वों के माध्यम से पुनरावृति कर सकते हैं । उदाहरण के लिए,

 // define Set const set = new Set((1, 2, 3)); // looping through Set set.forEach(myFunction); function myFunction(item) ( console.log(item); )

आउटपुट

 १ २ ३

मानचित्र के साथ आगे बढ़ें

आप forEach()विधि का उपयोग करके मैप तत्वों के माध्यम से पुनरावृति कर सकते हैं । उदाहरण के लिए,

 let map = new Map(); // inserting elements map.set('name', 'Jack'); map.set('age', '27'); // looping through Map map.forEach (myFunction); function myFunction(value, key) ( console.log(key + '- ' + value); )

आउटपुट

 नाम- जैक उम्र- 27

दिलचस्प लेख...