Type Checking Utilities
In this page:
$.isArray(value);
$.isFunction(value);
$.isNumeric(value);
$.type(value);
Type Checking क्या है?
jQuery $.isArray() और $.isFunction() जैसे छोटे utility functions देता है किसी value के underlying JavaScript type को reliably check करने के लिए, कुछ browser inconsistencies को काम में लाते हुए।
उदाहरण: What is Type Checking?
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
console.log($.isArray([1, 2, 3]), $.isFunction(function(){}));
</script>
</body>
</html>
Arrays Check करना
Arrays कई values को order में store करते हैं, और आपको अक्सर data मिलेगा — किसी form से, एक AJAX response से, या user input से — जहाँ आप पहले से sure नहीं हो सकते।
उदाहरण: Check Arrays
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
const data = [1, 2, 3];
console.log($.isArray(data));
</script>
</body>
</html>
Functions Check करना
Functions reusable code रखते हैं, और कभी-कभी आपको एक argument के रूप में एक value मिलेगी जो callable होनी चाहिए, जैसे एक optional callback parameter।
उदाहरण: Check Functions
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
function maybeCallback() { console.log("called"); }
if ($.isFunction(maybeCallback)) {
maybeCallback();
}
</script>
</body>
</html>
Objects Check करना
Objects related properties को एक साथ store करते हैं, जैसे किसी user का name और email एक value में। Type checking यह confirm करने में मदद करता है कि आप एक genuine object के साथ काम कर रहे हैं।
उदाहरण: Check Objects
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
const value = {name: "Alice"};
console.log($.type(value) === "object");
</script>
</body>
</html>
Practical Type Checking
Type checks खासतौर पर तब उपयोगी हो जाते हैं जब वही variable legitimately अलग-अलग shapes में आ सकता है, जैसे एक API जो कभी-कभी एक single।
उदाहरण: Practical Type Checking
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
function handle(data) {
if ($.isArray(data)) {
console.log("Got a list of", data.length);
} else {
console.log("Got a single item");
}
}
handle([1, 2, 3]);
</script>
</body>
</html>
- नए code में
$.isArray()और$.isFunction()इस्तेमाल करना, जबकि ये jQuery 3 में deprecated हैं औरArray.isArray()तथाtypeof x === "function"preferred हैं। typeof data === "array"से एक array check करना, जो कभी true नहीं होता क्योंकिtypeofarrays के लिए"object"return करता है।- यह मान लेना कि
$.isArray("apple")true है क्योंकि एक string में कई characters होते हैं, जबकि सिर्फ real arrays true return करते हैं।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: