字符串最大的數值,寫着玩

var test = 'a4sd34sdw3.9.2.1', result = "", p = "";
      for (var i = 0, len = test.length; i < len; i++) {
//          console.log(test[i]);
          //如果爲數字
          if (!isNaN(test[i])) {
              //第一次進入
              if (result == "") {
                  p = result = test[i];
              } else {
                  //如果上一值是數值或小數點
                  if (p != "") {
                      p = p + test[i];
                      if (parseFloat(result) < parseFloat(p)) {
                          result = p;
                      }
                      var pIndex = p.indexOf(".");
                      if (pIndex != -1) {
                          var decimal = p.substring(pIndex + 1, p.length);
                          if (parseFloat(result) < parseFloat(decimal)) {
                              result = decimal;
                          }
                      }
                  } else {
                      p = test[i];
                  }
              }
              //當前值爲小數點,與上一個值進行合判斷
          } else if (test[i] == ".") {
              if (p != "") {
                  var pIndex = p.indexOf(".");
                  if (pIndex != -1) {
                      p = p.substring(pIndex + 1, p.length);
                  }
                  p = p + test[i];
              }
          } else {
              p = "";
          }
      }

      console.log(result);

輸入pppp12bbbbbb12.31cccc,輸出31

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章