जावास्क्रिप्ट सरणी नक्शा () विधि हर सरणी तत्व के लिए एक फ़ंक्शन को कॉल करने के परिणामों के साथ एक नया सरणी बनाता है।
map()
विधि का सिंटैक्स है:
arr.map(callback(currentValue), thisArg)
यहाँ, अरै एक अरै है।
नक्शा () पैरामीटर
map()
विधि में लेता है:
- कॉलबैक - फ़ंक्शन हर ऐरे तत्व के लिए कहा जाता है। इसके रिटर्न मान नए सरणी में जोड़े जाते हैं। इसमें निम्न है:
- currentValue - वर्तमान तत्व सरणी से पास किया जा रहा है।
- यह आर्ग (वैकल्पिक) -
this
कॉलबैक निष्पादित करते समय उपयोग करने के लिए मूल्य । डिफ़ॉल्ट रूप से, यह हैundefined
।
मानचित्र से वापसी मूल्य ()
callback
प्रत्येक तत्व के लिए फ़ंक्शन से वापसी मान के रूप में तत्वों के साथ एक नया सरणी देता है ।
नोट :
map()
मूल सरणी नहीं बदलता है।map()
callback
प्रत्येक सरणी तत्व के लिए एक बार निष्पादित होता है।map()
callback
मूल्यों के बिना सरणी तत्वों के लिए निष्पादित नहीं करता है ।
उदाहरण 1: कस्टम फ़ंक्शन का उपयोग करके सरणी तत्वों को मैप करना
const prices = (1800, 2000, 3000, 5000, 500, 8000); let newPrices = prices.map(Math.sqrt); // ( 42.42640687119285, 44.721359549995796, 54.772255750516614, // 70.71067811865476, 22.360679774997898, 89.44271909999159 ) console.log(newPrices); // custom arrow function const string = "JavaScript"; const stringArr = string.split(''); // array with individual string character let asciiArr = stringArr.map(x => x.charCodeAt(0)); // map() does not change the original array console.log(stringArr); // ('J', 'a', 'v', 'a','S', 'c', 'r', 'i', 'p', 't') console.log(asciiArr); // ( 74, 97, 118, 97, 83, 99, 114, 105, 112, 116 )
आउटपुट
(42.42640687119285, 44.721359549995796, 54.772255750516614, 70.71067811865476, 22.360679774997898, 89-44271909999159) ('जे', 'ए', 'वी', 'ए', 'ए', 'ए', 'ए')। 't') (74, 97, 118, 97, 83, 99, 114, 105, 112, 116)
उदाहरण 2: नक्शा () सरणी में ऑब्जेक्ट तत्वों के लिए
const employees = ( ( name: "Adam", salary: 5000, bonus: 500, tax: 1000 ), ( name: "Noah", salary: 8000, bonus: 1500, tax: 2500 ), ( name: "Fabiano", salary: 1500, bonus: 500, tax: 200 ), ( name: "Alireza", salary: 4500, bonus: 1000, tax: 900 ), ); // calculate the net amout to be given to the employees const calcAmt = (obj) => ( newObj = (); newObj.name = obj.name; newObj.netEarning = obj.salary + obj.bonus - obj.tax; return newObj; ); let newArr = employees.map(calcAmt); console.log(newArr);
आउटपुट
((नाम: 'एडम', netEarning: 4500), (नाम: 'नूह', netEarning: 7000), (नाम: 'Fabiano', netEarning: 1800), (नाम: 'Alireza', netEarning: 4600)
नोट : यदि फ़ंक्शन लौटता है या कुछ भी नहीं है , तो नए सरणी में map()
असाइन करता undefined
है ।callback
undefined
अनुशंसित पढ़ना: जावास्क्रिप्ट ऐरे फ़िल्टर ()