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

जावास्क्रिप्ट सरणी forEach () विधि प्रत्येक सरणी तत्व के लिए प्रदान की गई फ़ंक्शन निष्पादित करती है।

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

 arr.forEach(callback(currentValue), thisArg)

यहाँ, अरै एक अरै है।

forEach () पैरामीटर्स

forEach()विधि में लेता है:

  • कॉलबैक - प्रत्येक ऐरे तत्व पर कार्य करने के लिए फ़ंक्शन। इसमें निम्न है:
    • currentValue - वर्तमान तत्व सरणी से पास किया जा रहा है।
  • यह आर्ग (वैकल्पिक) - thisकॉलबैक निष्पादित करते समय उपयोग करने के लिए मूल्य । डिफ़ॉल्ट रूप से, यह है undefined

फॉरच से वापसी मूल्य ()

  • लौटता है undefined

नोट :

  • forEach() मूल सरणी नहीं बदलता है।
  • forEach()callbackप्रत्येक सरणी तत्व के लिए एक बार निष्पादित होता है।
  • forEach()callbackमूल्यों के बिना सरणी तत्वों के लिए निष्पादित नहीं करता है ।

उदाहरण 1: मुद्रण सामग्री ऐरे की

 function printElements(element, index) ( console.log('Array Element ' + index + ': ' + element); ) const prices = (1800, 2000, 3000, , 5000, 500, 8000); // forEach does not execute for elements without values // in this case, it skips the third element as it is empty prices.forEach(printElements);

आउटपुट

 एरे तत्व 0: 1800 एरे तत्व 1: 2000 एरे तत्व 2: 3000 एरे तत्व 4: 5000 ऐरे तत्व 5: 500 एरे तत्व 6: 8000

उदाहरण 2: इस आर्ग का उपयोग करना

 function Counter() ( this.count = 0; this.sum = 0; this.product = 1; ) Counter.prototype.execute = function (array) ( array.forEach((entry) => ( this.sum += entry; ++this.count; this.product *= entry; ), this) ) const obj = new Counter(); obj.execute((4, 1, , 45, 8)); console.log(obj.count); // 4 console.log(obj.sum); // 58 console.log(obj.product); // 1440

आउटपुट

 ४ ५ १४४०

यहां, हम फिर से देख सकते हैं कि forEachखाली तत्व को छोड़ देता है। काउंटर ऑब्जेक्ट की विधि की परिभाषा के अंदर के thisArgरूप में पारित किया thisगया है execute

अनुशंसित पढ़ना: जावास्क्रिप्ट सरणी नक्शा ()

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