break
जावास्क्रिप्ट बताता switch
ब्लॉक में मामलों के मूल्यांकन को रोकने के लिए। कोड निष्पादन switch
ब्रैकेट बंद होने से पहले जारी है। उदाहरण कोड में return
कथन वास्तव में case
कथन और switch
ब्लॉक के बाद कुछ भी शामिल करने से पहले कुछ भी आगे रोक देगा।
मैंने आदत से हर मामले में break
स्टेटमेंट लगाया। अगर मैं एक break
बिना एक मामले में लिखा था तो मैं भविष्य है और एक break
बयान के अभाव में चारों ओर कॉपी कर सकते हैं और पेस्ट कोड के ब्लॉक तो जैसे एक बग बन जाएगा:
function whereLivesA(species){
switch(species){
case 'worms':
// Relying on return to prevent further code execution within the switch
// block works but is ~bad~ smelly (according to plato :D)
var habitat = 'dirt'
return (species + ' live in ' + habitat);
case 'bees':
var habitat = 'hive';
break;
}
// Stuff to do after the switch statement (unless you returned already)
var str = species+' live in '+habitat;
return str;
}
console.log('whereLivesA');
console.log(whereLivesA("worms"));
console.log(whereLivesA("bees"));
/* Output:
whereLivesA
worms live in dirt
bees live in hive
*/
function whereLivesB(species){
switch(species){
case "worms":
// what if future code changes remove `return` and don't add `break`?
// return (species + ' live in ' + habitat)
var habitat = 'dirt';
// break;
case "bees":
var habitat = 'hive'
break;
}
// Stuff to do after the switch statement (unless you returned already)
var str = species+' live in '+habitat;
return str;
}
console.log('whereLivesB');
console.log(whereLivesB("bees"));
console.log(whereLivesB("worms"));
/* Output:
whereLivesB
bees live in hive
worms live in hive
*/
function whereLivesCorrect(species){
switch(species){
case "worms":
var habitat = 'dirt';
break;
case "bees":
var habitat = 'hive'
break;
}
// Stuff to do after the switch statement (unless you returned already)
var str = species+' live in '+habitat;
return str;
}
console.log('whereLivesCorrect');
console.log(whereLivesCorrect("bees"));
console.log(whereLivesCorrect("worms"));
/* Output:
whereLivesCorrect
bees live in hive
worms live in dirt
*/
जे एस newbies: यदि आप ऐसा नहीं करते हैं इसे फ़ाइल में सहेजना और node filename
चलाएं, आप इसे चलाने के लिए F12 दबा सकते हैं और इस स्क्रिप्ट या अन्य स्वयं निहित स्क्रिप्ट को अपने ब्राउज़र के कंसोल में पेस्ट कर सकते हैं।
यदि आप node.js का उपयोग करते हैं तो आप node
को कमांड लाइन पर node
कंसोल शुरू करने और इसे पेस्ट करने के लिए भी टाइप कर सकते हैं।
यह _probably_ सिर्फ त्रुटियों को प्रतिलिपि करने/चिपकाने से परिणाम होगा और/या haphhazardly भविष्य में उस कोड को संशोधित करने के खिलाफ रोकने के लिए है:
यह एक विकल्प के लेखन शैली है कि कुछ लोगों का तर्क हो सकता है एक बेहतर अभ्यास है । मुझे एक अच्छी सुरक्षा नेट की तरह लग रहा है। – jahroy
इंडेंटेशन को देखते हुए, यह केवल स्टाइलिस्ट विकल्प हो सकता है - सुझाए गए [ब्लॉक] के अंत के रूप में 'ब्रेक' का उपयोग करके (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/वक्तव्य/ब्लॉक)। लेकिन, 'ब्रेक' 'वापसी' कथन के बाद पहुंच योग्य कोड है। तो, यह कुछ भी नहीं करेगा; लेकिन यह किसी भी चीज़ को चोट नहीं पहुंचाएगा। –