javascript實現一個數值加法函數

來源:互聯網
上載者:User

javascript實現一個數值加法函數

   這篇文章主要介紹了javascript實現一個數值加法函數,十分的簡單實用,方便大家理解javascript,有需要的小夥伴可以參考下。

  廢話不多說,直接奉上代碼

  JS

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

<script type="text/javascript">

function Sum(arg1,arg2){ //數值加法函數

var sarg1 = new String(arg1); //將傳入的參數轉為字串以便進行參數檢查

var sarg2 = new String(arg2); //將參數2轉為字元類型

if( (sarg1=="")||(sarg2=="") ) //確保參數不為空白

{

var e0 = new Error(); //當有參數為空白則拋出異常

e0.Serial = 1000001; //錯誤編號

if( sarg1=="" ) //根據為空白的參數正確填寫錯誤資訊

{

e0.message = "Sum函數參數非法:第1個參數為空白!"; //錯誤描述資訊

}

else

{

e0.message = "Sum函數參數非法:第2個參數為空白!";

}

throw e0; //拋出錯誤資訊

}

for(i=0;i<sarg1.length;i++){ //參數合法性檢查

for(j=0;j<10;j++){ //檢查所有字元

if(sarg1.charAt(i)==j) //若不是數字則拋出錯誤資訊

{

break; //跳出迴圈

}

else

{

if(j==9) //當已經查詢到數字9時

{

var e1 = new Error(); //錯誤資訊對象

e1.Serial = 1000001; //錯誤編號

e1.message = "Sum函數參數:" + sarg1 + "是非法數字!"; //錯誤描述資訊

throw e1;

}

}

}

}

for( k=0;k<sarg2.length;k++ ) //檢查參數2是數字

{

for(l=0;l<10;l++){ //從0到9逐一比較

if(sarg2.charAt(k)==l) //如果是0~9的數字

{

break;

}

else

{

if(l==9) //只有包含非數字則拋出錯誤資訊

{

var e2 = new Error(); //建立錯誤對象

e2.Serial = 1000001; //異常編號

e2.message = "Sum函數參數:" + sarg2 + "是非法數字!";

throw e2;

}

}

}

}

return Number(arg1) + Number(arg2); //參數都正確則返回兩個值得和

}

function Button1_onclick(){ //“計算”按鈕的單機事件處理常式

try{

var Text1 = document.getElementById("Text1");

var Text2 = document.getElementById("Text2");

var Text3 = document.getElementById("Text3");

var sum = Sum(Text1.value,Text2.value); //調用函數進行計算

 

Text3.value = sum; //輸出計算結果

}

catch(e){ //有錯誤發生則輸出錯誤資訊

alert(e.message); //輸出異常中的資訊

if(e.Serail == 1000001) //如果是1000001號錯誤

{

alert(e.message);

e = null;

}

}

}

</script>

  HTML:

  ?

1

2

3

4

5

6

<input type="text" id="Text1" style="width:84px" maxlength="20"/>

+

<input type="text" id="Text2" style="width:75px" maxlength="20"/>

=

<input type="text" id="Text3" style="width:69px">

<input type="button" id="Button1" value="計算" onclick="return Button1_onclick()" />

  以上所述就是本文的全部內容了,希望大家能夠喜歡。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.