mdn的apply的示例。从能做到用别人的库,好吧,是原生的库
/* 找出数组中最大/小的数字 */
var numbers = [5, 6, 2, 3, 7];
/* 应用(apply) Math.min/Math.max 内置函数完成 */
var max = Math.max.apply(null, numbers); /* 基本等同于 Math.max(numbers[0], ...) 或 Math.max(5, 6, ..) */
var min = Math.min.apply(null, numbers);
/* 代码对比: 用简单循环完成 */
max = -Infinity, min = +Infinity;
for (var i = 0; i < numbers.length; i++) {
if (numbers[i] > max)
max = numbers[i];
if (numbers[i] < min)
min = numbers[i];
}
复制代码
let json=[{ProcessType_1: "0.00",ProcessType_2: "0.00",ProcessType_3: "0.00"},{ProcessType_1: "0.00",ProcessType_2: "0.00",ProcessType_3: "0.00"},{ProcessType_1: "0.00",ProcessType_2: "0.00",ProcessType_3: "0.00"}];
json.forEach(elem,index){
let total;
let spanMax = 0;
let maxArr = [];
for(i in elem){
//求和
total+=elem[i]
//求最大值
if (spanMax == 0) {
if (elem[i] != 0) {
spanMax = elem[i];
maxArr[0] = i;
}
} else if (elem[i] > spanMax) {
spanMax = elem[i];
maxArr=[];//工作里的代码没想到这一步,当连续有两个值为暂时最大值,但当后面其实有真正最大值时,若不清空,则会得到重复而未清除的暂时最大值
maxArr[0] = i;
} else if (elem[i] == spanMax) {
maxArr.push(i);
}
};
//将得到的最大项的键值遍历添加class
maxArr.forEach(fucntion(el,ind){
$(el).addClass('特殊Class')
})
//先遍历一遍得到一行总值
for(i in elem){
let num=0;
if(total!=0){
num=elem[i]/total
}
得到最后的num塞入<span>
//最一步是在模板引擎中渲染进表格中实现,并非暴露在外面的代码
};
}
复制代码
- 需求中是需要先得到每个对应的百分数,求得最大值,将最大值设置特殊样式
- 工作中的代码还有瑕疵,求最大值和求总值可以放在一个循环中。
- 连续有两个值为暂时最大值
时间复杂度=O(n²);