javascript - 计算对象键值并将其转换为百分比(100%) [英] javascript - calculate and transform object key values into percentages (on 100%)

查看:40
本文介绍了javascript - 计算对象键值并将其转换为百分比(100%)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个对象:

myObj = {
    red: "332",
    green: "632",
    yellow: "14",
    brown: "45",
    pink: "83",
    violet: "21",
    gray: "100",
    black: "33",
    white: "200"
};

我需要计算这些对象键值并将其转换为百分比(100%)

I need to calculate and transform these object key values into percentages (on 100%)

有办法吗?

推荐答案

如果您希望根据最高数字获得百分比,这里有一个包含两个循环的示例(一个用于查找最大值,另一个用于更改实际值值):

If you wish to get the percentage based off the highest number, here is an example with two loops (one to finding the max value and the other for changing actual values):

var res = document.getElementById('r');
var myObj = {
    red: "332",
    green: "632",
    yellow: "14",
    brown: "45",
    pink: "83",
    violet: "21",
    gray: "100",
    black: "33",
    white: "200"
};

var max = 0;

for (var i in myObj) { // we find the max here
  if (parseInt(myObj[i], 10) > max) 
    max = myObj[i]; 
}

for (var i in myObj) { // we do the conversion here
  myObj[i] = (myObj[i] / max * 100) + "%";
  res.innerHTML += "<br>" + i + ": " + myObj[i]; // html output
}

<div id="r"></div>

如果你想得到总数的百分比(总数是所有值的总和):

And if you wish to get the percentages of total (total being the sum of all values):

var res = document.getElementById('r');
var myObj = {
    red: "332",
    green: "632",
    yellow: "14",
    brown: "45",
    pink: "83",
    violet: "21",
    gray: "100",
    black: "33",
    white: "200"
};

var total = 0;

for (var i in myObj) { // we find the total here
    total += parseInt(myObj[i], 10); 
}

for (var i in myObj) { // we do the conversion here
  myObj[i] = (myObj[i] / total * 100) + "%";
  res.innerHTML += "<br>" + i + ": " + myObj[i]; // html output
}

<div id="r"></div>

注意:您可能希望将这些数字四舍五入到较少的小数位数.

Note: you might want to round those numbers off to a fewer number of decimals.

这篇关于javascript - 计算对象键值并将其转换为百分比(100%)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆