简体   繁体   English

在js中使用Map,Reduce和filter将华氏温度转换为摄氏度

[英]What to use Map , Reduce and filter in js to convert fahrenheit to celcius

I have an array of temperatures and i have to convert them to degree celcius , i was told i need to use map/reduce in javascript .我有一系列温度,我必须将它们转换为摄氏度,有人告诉我我需要在 javascript 中使用 map/reduce。 I have looked through the documentation but i cant seem to figure out how to do it.我已经浏览了文档,但我似乎无法弄清楚如何去做。 Here is my array :这是我的数组:

var fahrenheit = [0, 32, 45, 50, 75, 80, 99, 120];

Try to use map in this way,尝试以这种方式使用map

var fahrenheit = [0, 32, 45, 50, 75, 80, 99, 120];
var celcius = fahrenheit.map(v => ((v - 32) * (5/9)).toFixed(1));
//If you do not want the decimal points then write,
//   fahrenheit.map(v => ((v - 32) * (5/9)) | 0);

console.log(celcius); //["-17.8", "0.0", "7.2", "10.0", "23.9", "26.7", "37.2", "48.9"]

Formula to convert F to C is,将 F 转换为 C 的公式是,

C = ((F - 32) * (5 / 9)) C = ((F - 32) * (5 / 9))

This should work这应该工作

  var celcius = fahrenheit.map(function(elem) {
        return Math.round((elem - 32) * 5 / 9);
    });

or in ES6或在 ES6 中

fahrenheit.map(elem => Math.round((elem - 32) * 5 / 9));

and you get你得到

celcius //  [-18, 0, 7, 10, 24, 27, 37, 49]

I guess this shall do it我想这会做到

var fahrenheit = [0, 32, 45, 50, 75, 80, 99, 120],
       celcius = fahrenheit.map(f => (f-32)/1.8);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM