我想将数组中的数字更改为百分比,但我不确定如何执行此操作。
var nums = [84394, 78952, 65570, 58097, 55673, 41847, 24884, 16567, 9966, 1689];
应该是:
var results = [84, 78, 65, 58, 55, 41, 24, 16, 9, 1]
我的尝试:
var nums = [84394, 78952, 65570, 58097, 55673, 41847, 24884, 16567, 9966, 1689];
var results = [];
for (var i = 0; i < nums.length; i++) {
var percentage = Math.floor(nums[i] / 100);
results.push(percentage).toFixed(2);
}
document.write(results.join(", "));
答案 0 :(得分:1)
阅读Array.prototype.map
和Bitwise OR (|
)。
var nums = [84394, 78952, 65570, 58097, 55673, 41847, 24884, 16567, 9966, 1689];
var convertToPercentages = function (arr, max) {
return nums.map(function (d, i) {
// time for some math
// we know the max is n
// so, to produce a whole-number percent
// we need to divide each digit `d` by `max`,
// then multiply by 100
// we then (`| 0`) to remove the decimals (same as Math.floor)
return (100 * d / max) | 0;
});
}
更好的方法(确定自己的最大值):
var getNearestPowerOfTen = function (arr) {
var max = arr.reduce(function (p, c) {
// is the previous less than the current item?
// if so, then return the current item
// otherwise, return the previous item
return p < c ? c : p;
}, 0);
// to find the next highest power of 10,
// we should return 10 raised to the number of digits
// in the integer part of our number
return Math.pow(10, (max | 0).toString().length);
}
var convertToPercentages2 = function (arr) {
var max = getNearestPowerOfTen(arr);
return nums.map(function (d, i) {
return (100 * d / max) | 0;
// could be more efficient with just
// `(d / max) | 0`, if you divide `max` by 100 above
});
}
更好的方法(因为我们无论如何都在做数学)
var getNearestPowerOfTen2 = function (arr) {
var max = arr[0];
// for-loop is faster than `Array.prototype.reduce`
for (var i = 1; i < arr.length; i++) {
if (max < arr[i]) max = arr[i];
}
return Math.pow(10, Math.ceil(Math.log10(max)));
}
答案 1 :(得分:1)
这应该有效:
var nums = [84394, 78952, 65570, 58097, 55673, 41847, 24884, 16567, 9966, 1689];
var results = [];
for(var i = 0; i < nums.length; i++) {
var divideBy = 0;
if ( nums[i] < 10000 )
divideBy = 100;
else if ( nums[i] < 100000 )
divideBy = 1000;
else if ( nums[i] < 1000000 )
divideBy = 10000;
else if ( nums[i] < 10000000 )
divideBy = 100000;
else if ( nums[i] < 100000000 )
divideBy = 1000000;
var percentage = Math.floor(nums[i] / divideBy);
results.push( percentage.toFixed(2) );
}
console.log(results);
答案 2 :(得分:0)
for(var i = 0; i < nums.length; i++) {
var percentage = parseInt((nums[i] + '').slice(0,2));
results.push( percentage );
}
答案 3 :(得分:0)
根据您的问题(所需结果),您的所有数字看起来都是3个精确浮点数乘以1000.
如果您希望根据下一个sig数字舍入结果:
/contacts/24552
&#13;
如果您只想要前两位数字:
var nums = [84394, 78952, 65570, 58097, 55673, 41847, 24884, 16567, 9966, 1689];
function roundedPercents(n){
return (n/1000).toFixed(0);
}
var roundedResults = nums.map(roundedPercents);
document.write(roundedResults.join(", "));
&#13;