Array Helper Utilities
In this page:
$.each(array, function (index, value) { /* ... */ });
$.grep(array, function (value) { return condition; });
$.inArray(value, array);
$.merge(array1, array2);
एक Array में Loop चलाना
$.each() किसी array के हर element (या किसी object की हर property) पर iterate करता है, प्रति item एक बार callback चलाते हुए और index व value pass करते हुए।
उदाहरण: Loop Through an Array
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
const fruits = ["Apple", "Banana"];
$.each(fruits, function(index, value) {
console.log(index, value);
});
</script>
</body>
</html>
एक Item ढूँढना
inArray utility किसी array में एक specific value search करता है और मिलने पर उसका numeric index return करता है, या मौजूद न होने पर -1, native Array के जैसा।
उदाहरण: Find an Item
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
const fruits = ["Apple", "Banana", "Cherry"];
console.log($.inArray("Banana", fruits));
</script>
</body>
</html>
Arrays Merge करना
merge utility दूसरे array के contents को पहले के अंत में append करके दो arrays को combine करता है, पहले array को in place modify करते हुए।
उदाहरण: Merge Arrays
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
const a = [1, 2];
const b = [3, 4];
$.merge(a, b);
console.log(a);
</script>
</body>
</html>
Array Values Filter करना
grep utility एक मौजूदा array से सिर्फ उन values वाला एक नया array बनाता है जो आपके दिए गए test function को pass करती हैं, native Array जैसा।
उदाहरण: Filter Array Values
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
const nums = [1, 2, 3, 4, 5];
const evens = $.grep(nums, function(n) { return n % 2 === 0; });
console.log(evens);
</script>
</body>
</html>
एक छोटा Array Project
ये array utilities तब उपयोगी हैं जब आप related items की एक list पर काम कर रहे हों — students, products, courses — और उन्हें search, combine, या filter करना हो।
उदाहरण: Small Array Project
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
const students = ["Alice", "Bob", "Charlie"];
const filtered = $.grep(students, function(name) { return name.startsWith("A"); });
console.log(filtered);
</script>
</body>
</html>
- एक
$.each()callback सेfalsereturn करना यह उम्मीद करते हुए कि यह एक item skip कर देगा, जबकि यह पूरा loop रोक देता है; skip करने के लिएreturn trueइस्तेमाल करें। $.inArray("kiwi", fruits)को true या false की तरह treat करना, जबकि यह एक index return करता है, इसलिएif ($.inArray(...))index 0 के लिए fail होता है और-1के लिए pass।$.merge(a, b)इस्तेमाल करना और यह उम्मीद करना किaunchanged रहेगा, जबकि यह पहले array को modify करके return करता है।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: