任意数求和:
function sum() {
var total = null;
for (var i = 0; i < arguments.length; i++) {
var cur = Number(arguments[i]);
if (!isNaN(cur)) {
total += cur;
}
}
return total;
}
2.数组去重(键值对)
var ary = [1, 2, 3, 3, 2, 3, 1, 2, 3, 4, 2, 3, 1, 2, 3, 2, 1, 2, 3];
var obj = {};
for (var i = 0; i < ary.length; i++) {
var cur = ary[i];
if (obj[cur] == cur) {
ary[i] = ary[ary.length - 1];
ary.length--;
i--;
continue;
}
obj[cur] = cur;
}
console.log(ary);
冒泡排序:
function bubbleSort(ary) {
var flag = false;
for (var i = 0; i < ary.length - 1; i++) {
for (var j = 0; j < ary.length - 1 - i; j++) {
if (ary[j] > ary[j + 1]) {
ary[j] = ary[j] + ary[j + 1];
ary[j + 1] = ary[j] - ary[j + 1];
ary[j] = ary[j] - ary[j + 1];
flag = true;
}
}
if (flag) {
flag = false;
} else {
break;
}
}
return ary;
}
console.log(bubbleSort([2, 1, 3, 5, 4]));
快速排序:
function quickSort(ary) {
if (ary.length <= 1) {
return ary;
}
var pointIndex = Math.floor(ary.length / 2);
var pointValue = ary.splice(pointIndex, 1)[0];
var left = [];
var right = [];
for (var i = 0; i < ary.length; i++) {
var cur = ary[i];
cur < pointValue ? left.push(cur) : right.push(cur);
}
return quickSort(left).concat([pointValue], quickSort(right));
}
var ary = [12, 13, 23, 14, 20, 26, 34, 13, 16];
var res = quickSort(ary);
console.log(res);
插入排序:
function insertSort(ary) {
var newAry = [];
newAry.push(ary[0]);
for (var i = 1; i < ary.length; i++) {
var cur = ary[i];
for (var j = newAry.length - 1; j >= 0;) {
if (cur < newAry[j]) {
j--;
if (j === -1) {
newAry.unshift(cur);
}
} else {
newAry.splice(j + 1, 0, cur);
j = -1;
}
}
}
return newAry;
}
利用对象的特性进行相数组去重排序。
var ary = [12, 23, 23, 12, 24, 34, 34, 23, 34, 5, 21, 2];
//->如果需求是既要去重也要排序,我们只需要利用对象的特点即可实现
var obj = {};
for (var i = 0; i < ary.length; i++) {
var cur = ary[i];
obj[cur] = cur;
}
var newAry = [];
for (var key in obj) {
newAry[newAry.length] = obj[key];
}
console.log(newAry);