जावास्क्रिप्ट ऐरे इंडेक्सऑफ़ ()

जावास्क्रिप्ट ऐरे इंडेक्सऑफ () विधि किसी सरणी तत्व के रोके जाने का पहला सूचकांक लौटाती है, या -1 नहीं मिलने पर।

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

 arr.indexOf(searchElement, fromIndex)

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

indexOf () पैरामीटर

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

  • searchElement - सरणी में पता लगाने वाला तत्व।
  • fromIndex (वैकल्पिक) - पर खोज शुरू करने के लिए सूचकांक। डिफ़ॉल्ट रूप से, यह 0 है

IndexOf से वापसी मान ()

  • यदि यह कम से कम एक बार मौजूद है, तो सरणी में तत्व का पहला सूचकांक लौटाता है।
  • तत्व में सरणी नहीं मिला है, तो रिटर्न -1

नोट: एरे के तत्वों की indexOf()तुलना सख्त समानता (ट्रिपल-बराबर ऑपरेटर या के समान) searchElementका उपयोग करके की जाती है ।===

उदाहरण 1: इंडेक्सऑफ () विधि का उपयोग करना

 var priceList = (10, 8, 2, 31, 10, 1, 65); // indexOf() returns the first occurance var index1 = priceList.indexOf(31); console.log(index1); // 3 var index2 = priceList.indexOf(10); console.log(index2); // 0 // second argument specifies the search's start index var index3 = priceList.indexOf(10, 1); console.log(index3); // 4 // indexOf returns -1 if not found var index4 = priceList.indexOf(69.5); console.log(index4); // -1

आउटपुट

 3 0 4 -1

टिप्पणियाँ:

  • यदि IndIndex> = array.length से , सरणी की खोज नहीं की जाती है और -1 लौटा दी जाती है।
  • यदि इंडेक्सेक्स 0 से , इंडेक्स पिछड़े की गणना करता है। उदाहरण के लिए, -1 अंतिम तत्व के सूचकांक और इतने पर निरूपित करता है।

उदाहरण 2: एक तत्व के सभी अवसरों का पता लगाना

 function findAllIndex(array, element) ( indices = (); var currentIndex = array.indexOf(element); while (currentIndex != -1) ( indices.push(currentIndex); currentIndex = array.indexOf(element, currentIndex + 1); ) return indices; ) var priceList = (10, 8, 2, 31, 10, 1, 65, 10); var occurance1 = findAllIndex(priceList, 10); console.log(occurance1); // ( 0, 4, 7 ) var occurance2 = findAllIndex(priceList, 8); console.log(occurance2); // ( 1 ) var occurance3 = findAllIndex(priceList, 9); console.log(occurance3); // ()

आउटपुट

 (0, 4, 7) (1) ()

उदाहरण 3: ढूँढना यदि तत्व मौजूद है तो तत्व जोड़ना

 function checkOrAdd(array, element) ( if (array.indexOf(element) === -1) ( array.push(element); console.log("Element not Found! Updated the array."); ) else ( console.log(element + " is already in the array."); ) ) var parts = ("Monitor", "Keyboard", "Mouse", "Speaker"); checkOrAdd(parts, "CPU"); // Element not Found! Updated the array. console.log(parts); // ( 'Monitor', 'Keyboard', 'Mouse', 'Speaker', 'CPU' ) checkOrAdd(parts, "Mouse"); // Mouse is already in the array.

आउटपुट

तत्व नहीं मिला! सरणी अद्यतन किया गया। ('मॉनिटर', 'कीबोर्ड', 'माउस', 'स्पीकर', 'सीपीयू') माउस पहले से ही ऐरे में है।

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

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