Javascript常见算法总结(持续更新)-爱代码爱编程
1、用JS手写快速排序
快排三步曲:
(1)在数据集之中,选择一个元素作为“基准”(pivot)。
(2)所有小于“基准”的元素,都移到“基准”的左边;所有大于“基准”的元素,都移到“基准”的右边。
(3)对"基准"左边和右边的两个子集,不断重复第一步和第二步,直到所有子集只剩下一个元素为止。
var arr = [55, 66, 18, 10, 20, 30, 1, 2, 3, 12, 2];
var result = quickSort(arr);
console.log('结果: ' + result);
function quickSort(tempArr) {
if (tempArr.length <= 1) {
return tempArr;
}
//第一步取基准值
var midIndex = Math.floor(tempArr.length / 2);
var midValue = tempArr.splice(midIndex, 1);
console.log(midValue);
//第二步分左右
var left = [];
var right = [];
for (var i = 0; i < tempArr.length; i++) {
if (midValue > tempArr[i]) {
left.push(tempArr[i]);
} else {
right.push(tempArr[i]);
}
}
console.log('left:',left, 'midValue:' + midValue, 'right:', right);
//第三步 重复第一步和第二步
// console.log(left.concat(midValue, right));
return quickSort(left).concat(midValue, quickSort(right));
}
2、判断一个字符串中出现次数最多的字符,统计这个次数
var str = '112223333iiiii';
var obj = {};
for (var i = 0; i < str.length; i++) {
obj[str[i]] ? obj[str[i]]++ : obj[str[i]] = 1;
}
console.log(obj);
var maxCount = 0;
var keyStr = '';
for (var key in obj) {
if (obj[key] > maxCount) {
maxCount = obj[key];
keyStr = key;
}
}
console.log('出现最多的字符是:'+keyStr, '次数是:' + maxCount);
3、Javascript面向对象中继承实现
在js中使用原型实现继承。将子类的原型设置为父类的一个具体实例
function HTTPRequest(){
}
HTTPRequest.prototype.HTTPGET = function () {
console.log('GET');
};
HTTPRequest.prototype.HTTPPOST = function () {
console.log('POST');
}
var httpRequest = new HTTPRequest();
//注册
function Register(){
}
Register.prototype = httpRequest;
//登陆
function Login(){
}
Login.prototype = httpRequest;
//退出
function Logout(){
}
Logout.prototype = httpRequest;
/**
* 注册
*/
var reg = new Register();
reg.HTTPGET();
reg.HTTPPOST();
4、数组去重
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, '1', '2'];
result = [];
hash = {};
var type = '';
for (var i = 0; i < arr.length; i++) {
type = typeof arr[i];
if (!hash[arr[i]+type]) {
result.push(arr[i]);
hash[arr[i]+type] = 200;
}
}
console.log(result);
console.log(hash);//{1number: 200, 2number: 200, 3number: 200, 4number: 200, 5number: 200, …}
5、类型检测(函数实现)
1.检测string类型
function checkString(obj) {
return typeof(obj) == "string";
}
alert(checkString(666));
alert(checkString("666"));
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 本文链接: https://blog.csdn.net/huohuoit/article/details/106243861