1、js中json对象和字符串的转换
JSON.parse() : 字符串-->json对象
JSON.stringify() : json对象-->字符串
2、'JS 中如何判断 undefined
JavaScript 中有两个特殊数据类型:undefined 和 null,下节介绍了 null 的判断,下面谈谈 undefined 的判断。
以下是不正确的用法:
var exp = undefined; if (exp == undefined) { alert("undefined"); }
exp 为 null 时,也会得到与 undefined 相同的结果,虽然 null 和 undefined 不一样。注意:要同时判断 undefined 和 null 时可使用本法。
var exp = undefined; if (typeof(exp) == undefined) { alert("undefined"); }
以下是正确的用法:
var exp = undefined; if (typeof(exp) == "undefined") { alert("undefined"); }
3、JS 中如何判断 null
以下是不正确的用法:
var exp = null; if (exp == null) { alert(“is null”); } exp 为 undefined 时,也会得到与 null 相同的结果,虽然 null 和 undefined 不一样。注意:要同时判断 null 和 undefined 时可使用本法。 var exp = null; if (!exp) { alert(“is null”); } 如果 exp 为 undefined 或者数字零,也会得到与 null 相同的结果,虽然 null 和二者不一样。注意:要同时判断 null、undefined 和数字零时可使用本法。 var exp = null; if (typeof(exp) == “null”) { alert(“is null”); } 为了向下兼容,exp 为 null 时,typeof 总返回 object。 var exp = null; if (isNull(exp)) { alert(“is null”); } JavaScript 中没有 isNull 这个函数。
以下是正确的用法:
var exp = null; if (!exp && typeof(exp)!=”undefined” && exp!=0) { alert(“is null”); }
尽管如此,我们在 DOM 应用中,一般只需要用 (!exp) 来判断就可以了,因为 DOM 应用中,可能返回 null,可能返回 undefined,如果具体判断 null 还是 undefined 会使程序过于复杂。
4、JS去掉字符串前后空格或去掉所有空格的用法
1、使用string.trim()
string.trim()
浏览器版本限制:JavaScript Version 1.8
1、 去掉字符串前后所有空格:
function Trim(str) { return str.replace(/(^\s*)|(\s*$)/g, ""); }
说明:
如果使用jQuery直接使用$.trim(str)方法即可,str表示要去掉前后所有空格的字符串。
2、 去掉字符串中所有空格(包括中间空格,需要设置第2个参数为:g)
function Trim(str,is_global) { var result; result = str.replace(/(^\s+)|(\s+$)/g,""); if(is_global.toLowerCase()=="g") { result = result.replace(/\s/g,""); } return result; }
3、现在大部分浏览器中基本上都支持字符串的 trim 函数,但是为了兼容不支持的浏览器,我们最好还是在 Js 文件中加入以下代码(不需要清除换行符的请删除 \n 制表符删除 \t):
if (!String.prototype.trim) { /*--------------------------------------- * 清除字符串两端空格,包含换行符、制表符 *---------------------------------------*/ String.prototype.trim = function () { return this.triml().trimr(); } /*---------------------------------------- * 清除字符串左侧空格,包含换行符、制表符 * ---------------------------------------*/ String.prototype.triml = function () { return this.replace(/^[\s\n\t]+/g, ""); } /*---------------------------------------- * 清除字符串右侧空格,包含换行符、制表符 *----------------------------------------*/ String.prototype.trimr = function () { return this.replace(/[\s\n\t]+$/g, ""); } }
如果只需要 trim 函数的,可以只写一个:
if (!String.prototype.trim){ /*--------------------------------------- * 清除字符串两端空格,包含换行符、制表符 *---------------------------------------*/ String.prototype.trim = function () { return this.replace(/(^[\s\n\t]+|[\s\n\t]+$)/g, ""); } }
使用代码:
var str = " abcd ".trim();
还没有评论,来说两句吧...