js数组学习
1、用传统老思路写返回数组最大值。
*
* @param level 全集数组
* @describe 函数用于循环比较得出数组里面的最大值。
* @author 908637150@qq.com
* @createDate 2017年8月11日 下午9:40:00
* */
function loopLevel(level){
var compareNum = 0;
for(var i=0; i < level.length; i++){
compareNum = compareNumber(parseInt(compareNum), parseInt(level[i]));
}
return compareNum;
}
/*
*
* @param a 子集数组
* @param b 全集数组
* @describe 函数用来比较两个数大小
* @author 908637150@qq.com
* @createDate 2017年8月11日 下午9:40:00
* */
function compareNumber(a, b){
}
2、用prototype来扩展数组对象方法来实现
*
* @describe 获取数组的最小值
* @author 908637150@qq.com
* @createDate 2017年8月11日 下午9:40:00
* */
Array.prototype.min = function(){
var min = this[0];
for(var i=0; i <this.length; i++){
if(this[i] < min){
min = this[i];
}
}
return min;
}
/*
*
* @describe 获取数组的最大值
* @author 908637150@qq.com
* @createDate 2017年8月11日 下午9:40:00
* */
Array.prototype.max = function(){
var max = this[0];
for(var i=0; i <this.length; i++){
if(this[i] > max){
max = this[i];
}
}
return max;
}
compareNum = loopLevel(level);
console.log(level.max());
3、数组去重。
/*
*
* @describe unique通过prototype原型链扩张的数组函数,作用用于去掉重复数组。
* @author 908637150@qq.com
* @createDate 2017年8月11日 下午9:40:00
* */
Array.prototype.unique = function() {
var newArr = [this[0]]; //数组结果
for(var i = 0, len = this.length; i < len; i++) {
var repeat = false; //设置重复参数
for(var j = 0, len2 = newArr.length; j < len2; j++) {
if(this[i] == newArr[j]) {
repeat = true; //若重复设置为true
break;
}
}
//去重push数组
if(!repeat) {
newArr.push(this[i]);
}
}
return newArr;
};
/*
*
* @param arrays 子集数组
* @param zNodes 全集数组
* @param TEMP 时变量用于保存递归循环出来的数组集合
* @param OLDARR 临时变量用于保存循环前的数组集合
* @function arrChild 返回递归子集数组
* @function concat 全集数组
* @describe arrCom函数功能:遍历全集,判断递归返回子集数组中第零个数组集中的元素pId是否为零(递归终止条件),不为零调用arrChild函数返回子集,
* @author 908637150@qq.com
* @createDate 2017年8月11日 下午9:40:00
* */
function arrCom(arrays){
var TEMP = [];
var OLDARR = arrays;
for (var j = 0; j < zNodes.length; j++) {
if(arrays[0].pId != 0) {
arrChild(arrays, zNodes);
arrays = arrChild(arrays, zNodes);
temps = OLDARR.concat(arrays);
}
TEMP = TEMP.concat(temps);
TEMP = TEMP.unique(TEMP);
}
return TEMP;
}
/*
*
* @param arrays 子集数组
* @param zNodes 全集数组
* @describe arrChild函数功能:遍历子集,根据子集数组的pId与全集数组id进行匹配,然后返回匹配结果集。
* @author 908637150@qq.com
* @createDate 2017年8月11日 下午9:40:00
* */
function arrChild(arrays, zNodes){
var Child = [];
for (var f = 0; f < arrays.length; f++) {
for (var g = 0; g < zNodes.length; g++) {
if (arrays[f].pId == zNodes[g].id) {
Child.push(zNodes[g]);
}
}
}
Child = Child.unique(Child);
return Child;
}
/*
*
* @describe unique通过prototype原型链扩张的数组函数,作用用于去掉重复数组。
* @author 908637150@qq.com
* @createDate 2017年8月11日 下午9:40:00
* */
var CHELIDARRAY = [];
for (var i = 0; i < zNodes.length; i++) {
if(zNodes[i].orgFlag == "2") {
CHELIDARRAY.push(zNodes[i]);
}
}
var yy = CHELIDARRAY.unique(CHELIDARRAY);