gpt4 book ai didi

javascript:N维数组的四舍五入数值

转载 作者:太空宇宙 更新时间:2023-11-04 15:40:10 25 4
gpt4 key购买 nike

我需要以给定的精度对数组中的值进行舍入。数组可以包含任何数据类型,因此非数字值应保持“原样”。需要两位小数的数组示例:

function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}

function roundNumericValuesInArray(array, precision){
var roundedArray = [];

array.forEach(function round(elem){
if(isNumber(elem)) {
roundedArray.push(elem.toFixed(precision));
} else{
roundedArray.push(elem);
}
})

return roundedArray;
}
var simpleArray = [5.454545, 8.456545646, true, 'fff'];
console.log(roundNumericValuesInArray(simpleArray, 2));
//["5.45", "8.46", true, "fff"]

适用于一维数组,但是当数组包含另一个数组作为其元素时,此代码将无法正常工作,内部数组中的值将不会被舍入:

var twoDimensionalArray = [5.48878533, 4.8798765, [5.4843, 9.498787878, 'fff'], 5.4852, true];
console.log(roundNumericValuesInArray(twoDimensionalArray, 2));
// ["5.49", "4.88", [5.4843, 9.498787878, 'fff'], "5.49", true]

如果 elem 是数组,我尝试通过递归调用 round() 函数来解决这个问题,如下所示:

function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}

function roundNumericValuesInArray(array, precision){
var roundedArray = [];

array.forEach(function round(elem){
if(isNumber(elem)) {
roundedArray.push(elem.toFixed(precision));
} else if(elem.constructor === Array){
round(elem);
} else {
roundedArray.push(elem);
}
})

return roundedArray;
}

但是解释器抛出“RangeError:超出最大调用堆栈大小”,因此它变成无限循环或其他东西:

var twoDimensionalArray = [5.48878533, 4.8798765, [5.4843, 9.498787878, 'fff'], 5.4852, true];
console.log(roundNumericValuesInArray(twoDimensionalArray, 2));
//Maximum call stack size exceeded

这就是问题所在:对多维数组中的数字元素进行舍入,无论它们有多深。

输出

[5.48878533, 4.8798765, [5.4843, 9.498787878, 'fff'], 5.4852, true]

应该是这样的

[5.48, 4.87, [5.48, 9.49, 'fff'], 5.48, true]

最佳答案

如果是数组,请将其传递给 roundNumericValuesInArray() 并将结果推送到 roundedArray

if(elem.constructor === Array){
roundedArray.push(roundNumericValuesInArray(elem, precision));
}

function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}

function roundNumericValuesInArray(array, precision){
var roundedArray = [];

array.forEach(function round(elem){
if(isNumber(elem)) {
roundedArray.push(elem.toFixed(precision));
} else if(elem.constructor === Array){
roundedArray.push(roundNumericValuesInArray(elem, precision));
} else {
roundedArray.push(elem);
}
})

return roundedArray;
}

var twoDimensionalArray = [5.48878533, 4.8798765, [5.4843, 9.498787878, 'fff', [1.2345, 2]], 5.4852, true];
console.log(roundNumericValuesInArray(twoDimensionalArray, 2));

关于javascript:N维数组的四舍五入数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43952126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com