JavaScript 容易出问题的地方:
(1)把json 字符串转化为对象
- var jsonStr='{"2":"1.2.3","3":"1.2.5"}';
- var jsonObj2=eval("("+jsonStr+")");
注意:使用eval时,一定要在json字符串前后加上小括号
(2)
遍历js 对象属性
- var jsonStr='{"2":"1.2.3","3":"1.2.5"}';
- var jsonObj2=eval("("+jsonStr+")");
- for(temp in jsonObj2){
- alert(temp);
- }
说明:temp的取值为2和3. jsonStr的类型是string,jsonObj2的类型是object
(3)判断js变量是否有值
- /**
- * whether has value
- *
- * @param {Object}
- * input
- */
- isHasValue = function(input) {
- if (typeof input == "number" && input == "0") {
- return true;
- }
- if (input == "" || input == undefined
- || com.whuang.hsj.isWholeWhitespace(input)) {
- return false;
- }
- return true;
- };
- isWholeWhitespace = function(inputString) {
- if (typeof inputString == "object") {
- return inputString;
- }
- var bootInit = true;
- if (inputString == "" || inputString == undefined) {
- return false;
- }
- for ( var i = 0; i < inputString.length; i++) {
- var c = inputString.charAt(i);
- if (!com.whuang.hsj.isWhitespace(c)) {
- bootInit = false;
- break;
- }
- }
- return bootInit;
- };
(4)把对象转化为json字符串
- object2jsonStr=function(requestObj)
- {
- return JSON.stringify(requestObj);
- };
(5)把表单提交的query string转化为对象
- /***
- * convert [request query string] to [js object]
- */
- var queryString2Object=function(queryString)
- {
- if(queryString==''||queryString==undefined)
- {
- return null;
- }
- var queryArray=queryString.split('&');
- var queryObj=new Object();
- for(var i=0;i<queryArray.length;i++)
- {
- var oneQuery=queryArray[i];
- var oneQueryKeyValue=oneQuery.split('=');
- if(oneQueryKeyValue.length>1)
- {
- queryObj[oneQueryKeyValue[0]]=oneQueryKeyValue[1];
- }
- }
- return queryObj;
- };
测试:
- var queryString="name1=value1&name2=&name3=value3&name4=value4";
- var a=com.whuang.hsj.queryString2Object(queryString);
- alert(a.name1);