js常用数据转换&判断
- 数组转字符串
var a, b;
a = new Array(0,1,2,3,4);
b = a.join("-"); //"0-1-2-3-4"
- 字符串转数组
var s = "abc,abcd,aaa";
ss = s.split(",");// 在每个逗号(,)处进行分解 ["abc", "abcd", "aaa"]
var s1 = "helloworld";
ss1 = s1.split(''); //["h", "e", "l", "l", "o", "w", "o", "r", "l", "d"]
- 转成num
Number(this.totalPage)
- 转为整型
parseInt(num)
- 转换成变量名
eval('items' + this.userType)
判断一个字符串是否存在于一个字符串数组中
1. 正则表达式
Array.prototype.in_array=function(e){
var r=new RegExp(','+e+',');
return (r.test(','+this.join(this.S)+','));
};
arr.in_array('b');
注:此函数只对字符和数字有效
2. 遍历
Array.prototype.in_array = function (element) {
for (var i = 0; i < this.length; i++) {
if (this[i] == element) {
return true;
}
}
return false;
}
arr.in_array('test');
3. indexOf()
function IsInArray(arr,val){
var testStr=','+arr.join(",")+",";
return testStr.indexOf(","+val+",")!=-1;
}
IsInArray(arr,'test');
注:IE9以下不支持Array的indexOf