ဖြေရှင်းထားသည်- စာကြောင်းတွင် ကိန်းပြည့်ဂဏန်းများသာ javascript ပါရှိမရှိ စစ်ဆေးပါ။

စာကြောင်းတစ်ကြောင်းတွင် ကိန်းပြည့်ဂဏန်းများသာ ပါရှိမရှိ စစ်ဆေးခြင်းတွင် အဓိကပြဿနာမှာ ၎င်းကို မည်သို့ပြုလုပ်ရန် သတ်မှတ်ထားသော စံသတ်မှတ်ချက်မရှိခြင်းပင်ဖြစ်သည်။ ၎င်းသည် ကွဲပြားသော အကောင်အထည်ဖော်မှုများကို ကွဲပြားခြားနားသော ရလဒ်များ ပြန်လာစေပြီး နားလည်ရန် ခက်ခဲနိုင်ပြီး အမှားရှာပြင်နိုင်သည်။

I want to check if a string only contains integer digits numbers.
For example:
<code>var str = "123"; // return true;
var str = "123a"; // return false;
</code>


A:

You can use <code>/^d+$/.test(str)</code>.  This will test whether the string consists of one or more digits.  If you want to allow for a leading minus sign, then use <code>/^-?d+$/.test(str)</code>.  If you want to allow for an optional decimal point and fractional part, then use <code>/^-?d+(.d+)?$/.test(str)</code>.  If you want to allow for an optional exponent, then use <code>/^-?(d+(.d*)?|.d+)([eE][-+]?d+)?$/.test(str)</code>.  The last two expressions are the ones used by the built-in function <code>isFinite()</code>, which is what you should be using if your goal is to test whether a string can be converted into a number.  (If your goal is something else, please edit your question.)

ခြွင်းချက်

Conditionals များသည် JavaScript တွင် အစွမ်းထက်သော tool တစ်ခုဖြစ်သည်။ ၎င်းတို့သည် သင့်အား အချို့သောအခြေအနေများပေါ်မူတည်၍ သင့်ကုဒ်စီးဆင်းမှုကို ထိန်းချုပ်နိုင်စေပါသည်။

conditionals အတွက် အသုံးများသော အသုံးတစ်ခုမှာ variable တစ်ခုသည် အချို့သောတန်ဖိုးနှင့် ညီမျှခြင်းရှိ၊မရှိ စစ်ဆေးရန်ဖြစ်သည်။ ဥပမာအားဖြင့်၊ အသုံးပြုသူ၏ထည့်သွင်းမှု မမှန်ကန်ပါက သင်သည် အမှားအယွင်း မက်ဆေ့ချ်ကို ပြသလိုပေမည်။

အခြေအနေတစ်ခုမှန်လား မှားလားဆိုတာကို စမ်းသပ်ဖို့ if statement ကိုသုံးနိုင်ပါတယ်။ အောက်ဖော်ပြပါ ကုဒ်နမူနာသည် အသုံးပြုသူ၏ ထည့်သွင်းမှုသည် 1 နှင့် 10 ကြားရှိမရှိ စစ်ဆေးပေးသည်-

if (userInput <= 10) { // error message တစ်ခုကို ပြသခြင်း } else { // ပုံမှန် တုံ့ပြန်မှုကို ပြသခြင်း } အခြေအနေများစွာကို တစ်ပြိုင်နက် စမ်းသပ်ရန် switch statement ကို သင်လည်း အသုံးပြုနိုင်ပါသည်။ အောက်ဖော်ပြပါ ကုဒ်နမူနာသည် အသုံးပြုသူ၏ ထည့်သွင်းမှုသည် 1 နှင့် 10 ကြား၊ အနည်းဆုံး အက္ခရာ 3 လုံး အရှည်ရှိမရှိ စစ်ဆေးပြီး စာလုံးတစ်ခုဖြင့် စတင်သည်- switch (userInput) { case "1": case "2": case "3": case "a": case "b": case "c": break; မူရင်း: // အမှားမက်ဆေ့ချ်ကို ပြသပါ }

ရပြီလား

အကယ်၍ JavaScript တွင် conditional operator တစ်ခုဖြစ်သည်။ ၎င်းသည် သင့်အား ဖြစ်နိုင်ချေရှိသော ရလဒ်နှစ်ခုကြားတွင် ရွေးချယ်နိုင်စေပါသည်။ ပထမရလဒ်သည် အခြေအနေဖြစ်ပြီး ဒုတိယရလဒ်သည် if statement ၏ရလဒ်ဖြစ်သည်။

နံပါတ်တစ်ခုသည် လုံးခြင်း သို့မဟုတ် ထူးဆန်းခြင်းရှိမရှိ စစ်ဆေးလိုပါက အောက်ပါကုဒ်ကို အသုံးပြုနိုင်ပါသည်။

အကယ်၍ (နံပါတ် %2 == 0) { //even } else { //odd }

နံပါတ်တစ်ခုမဟုတ်ပါက အခြားအပိုဒ်သည် လည်ပတ်မည်ဖြစ်သည်။

Related ရေးသားချက်များ:

a Comment ချန်ထား