冒泡排序法
var arrays = [81, 23, 46, 11, 56, 69, 57, 78, 99, 21, 23];
for (var i = 0; i < arrays.length - 1; i++) {
for (var j = 0; j < arrays.length - 1 - i; j++) {
if (arrays[j] > arrays[j + 1]) {
var t = arrays[j + 1];
arrays[j + 1] = arrays[j];
arrays[j] = t;
}
}
}
选择排序法
var arrays = [81, 23, 46, 11, 56, 69, 57, 78, 99, 21, 23];
//选择排序法
for (var i = 0; i < arrays.length - 1; i++) {
for (var j = i + 1; j < arrays.length; j++) {
if (arrays[i] > arrays[j]) {
var t = arrays[i];
arrays[i] = arrays[j];
arrays[j] = t;
}
}
}
console.log(arrays);
函数柯里化
// 函数柯里化:利用返回函数的方式,将多个参数进行分解,单一参数。
// 普通函数
function add(x, y) {
return x + y;
}
// 函数柯里化
function add(x) {
return function(y) {
return x + y;
};
}
console.log(add(1)(2))
// 函数柯里化封装
function add(x, y) {
return x + y;
}
function curried(fn, ...arg1) {
return function(...arg2) {
return fn(...arg1, ...arg2);
};
}
var increment = curried(add, 1);
console.log(increment(2));
// 函数柯里化更适合函数式编程方法
new 实现原理
function myFun() {
}
var f = new myFun();
console.log(f instanceof myFun);
console.log(_instanceof(f, myFun));
var s = "str"
console.log(_instanceof(s, String));
console.log(s instanceof String);
function _instanceof(left, right) {
var left = left.__proto__;
var prototype = right.prototype;
while (true) {
if (left == null) {
return false;
}
if (left == prototype) {
return true;
}
left = left.__proto__;
}
}
数组去重
var arr = [2,5,3,6,2,4,5,8,3]
var obj = {}
for (var i = 0; i < arr.length; i++) {
if(!obj[arr[i]]){
obj[arr[i]] = 1
}
}
console.log(obj)
斐波那契数列
function fibonacci(n) {
return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
}
console.log(fibonacci(5)) // 1 1 2 3 5
JavaScript深拷贝
var obj1 = {
o: {
name: "hello"
},
arr: [1, 2, {
pass: 333
}],
str: "world"
};
function isType(target) {
return Object.prototype.toString.call(target).slice(8, -1);
}
function deepCopy(target) {
var type = isType(target);
var reslut;
if (type === "Array") {
reslut = [];
} else if (type === "Object") {
reslut = {};
} else {
return target
}
for (var key in target) {
var value = target[key];
if (isType(value) === "Object" || isType(value) === "Array") {
reslut[key] = deepCopy(value);
} else {
reslut[key] = value;
}
}
return reslut;
}
var obj2 = deepCopy(obj1);
obj2.o.name = "hello x";
obj2.arr[0] = 11;
obj2.arr.push(4);
obj2.arr[2].pass = 555;
obj2.str = "world x";
console.log("new obj1", obj1);
console.log("new obj2", obj2);
统计出现组多的元素
var arr = ["1", "2", "345", "3", "21", "345","4", "23", "88", "25", "2", "3", "99"];
var maxStack = {};
for (var i = 0; i < arr.length; i++) {
var item = arr[i];
if (!maxStack[item]) {
maxStack[item] = 1;
} else {
maxStack[item] = maxStack[item] + 1;
}
}
console.log(maxStack);