精简String和Array

如何去掉字符串"hi,jjjjjaaaaaaavasssscrrrippppt"中重复的字母,变成"hi, javascript"呢?

 

var compatString = function(str) { var pattern = /(/w)/1+/g, matched; while ((matched = pattern.exec(str)) !== null) { str = str.replace(matched[0], matched[1]); pattern.lastIndex = pattern.lastIndex - matched[0].length; } return str; }; //测试 var str = "hi,jjjjjaaaaaaavasssscrrrippppt"; window.alert(compatString(str));

 

 

如何去掉数组中的重复项,将[ 100, 20, 23, 40, 200, 30, 23, 0, 20, 23 ]简化成[ 100, 20, 23, 40, 200, 30, 0 ] (可以顺序不一致)呢?

var compactArray = function(arr) { var temp = [ arr[0] ], i, j, isPush = true; for (i = 1; i < arr.length; i++) { for (j = 0; j < temp.length; j++) { (arr[i] === temp[j]) && (isPush = false); } isPush && temp.push(arr[i]); isPush = true; } return temp; }; //测试 var arr = [ 100, 20, 23, 40, 200, 30, 23, 0, 20, 23 ]; window.alert(compactArray(arr));

 

其实问题很简单,却失误了,记住教训!(增强记忆力)

 

 

你可能感兴趣的:(JavaScript,String,function,测试,null)