圆数而不是小数

时间:2017-03-09 21:07:45

标签: javascript math

我只需要使用以下函数从数据变量中删除小数。目前似乎无法管理它。

maths.multiplyInteger = function(sequence) {
        if (sequence.length == 0) {
            return 0;
        }

        var result = maths.getInteger(sequence[0]);

        function loop(data) {
            for (var i = 1, length = sequence.length; i < length; i++) {
                var result = result * maths.getInteger(sequence[i]);
            }
        }

        loop(sequence);

        return {
            input: sequence,
            output: result
        }
    };

数据变量如下所示:

 var data = {
        first: [3.57, 2.43, '043'],
        second: [7.26, 1.43, '025'],
        third: ['076', 3.0, 6.42],
    };

2 个答案:

答案 0 :(得分:4)

Math.floor()工作正常,但首先你必须正确引用这些元素。建议的方法:Object.keys()Array#map

var data = {
  first: [3.57, 2.43, '043'],
  second: [7.26, 1.43, '025'],
  third: ['076', 3.0, 6.42],
},
res = {};

Object.keys(data).forEach(function(v){
  res[v] = data[v].map(c => Math.floor(c)).reduce((a,b) => a * b);
})

console.log(res);

//Object.keys() function returns array of all keys of the data object, it will look
//like: ['first', 'second', 'third']
//Then, use map function to iterate over it to catch every key value,
//which is an array (for example - [3.57, 2.43, '043']
//Then, catch every element in this array with map function and round it down
//using Math.floor() function (to the nearest integer under)

答案 1 :(得分:1)

您可以映射Math.floor的结果。

var data = { first: [3.57, 2.43, '043'], second: [7.26, 1.43, '025'], third: ['076', 3.0, 6.42] },
    result = Object.keys(data).map(function (k) { return data[k].map(Math.floor); });

console.log(result);