Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/447.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 我需要写一个函数,它接受一个华氏度的参数,并将其转换为摄氏度_Javascript - Fatal编程技术网

Javascript 我需要写一个函数,它接受一个华氏度的参数,并将其转换为摄氏度

Javascript 我需要写一个函数,它接受一个华氏度的参数,并将其转换为摄氏度,javascript,Javascript,这是我的代码: function convertFahrToCelsius(temp) { if(typeof(temp) === "number" || typeof(temp) === "string"){ return ((Number(temp) - 32) * 5/9).toFixed(4); } else { return `${temp} is not a valid number but a/an ${typeof(

这是我的代码:

function convertFahrToCelsius(temp) {
  if(typeof(temp) === "number" || typeof(temp) === "string"){
    return ((Number(temp) - 32) * 5/9).toFixed(4);
  } else {
    return `${temp} is not a valid number but a/an ${typeof(temp)}`;
  }
}

console.log(convertFahrToCelsius(0));
console.log(convertFahrToCelsius("0") );
console.log(convertFahrToCelsius([1,2,3]));
console.log(convertFahrToCelsius({temp: 0}));
这应该是输出:

- convertFahrToCelsius(0) should return `-17.7778`
- convertFahrToCelsius("0") should return `-17.7778`
- convertFahrToCelsius([1,2,3]) should return `[1,2,3] is not a valid number but a/an array.`
- convertFahrToCelsius({temp: 0}) should return `{temp: 0} is not a valid number but a/an object.`
这是我的输出:

- convertFahrToCelsius(0);: -17.7778
- convertFahrToCelsius("0");:-17.7778
- convertFahrToCelsius([1,2,3]);:1,2,3 is not a valid number but a/an object
- convertFahrToCelsius({temp: 0});:[object Object] is not a valid number but a/an object
我需要最后两个输出与应该的相同。

试试JSON.stringify()

函数转换器温度(摄氏度){
如果(类型(临时)==“数字”| |类型(临时)==“字符串”){
返回(编号(临时)-32)*5/9.toFixed(4);
}否则{
返回`${JSON.stringify(temp)}不是有效数字,而是一个${typeof(temp)}`;
}
}
console.log(0);
console.log(0);
log(摄氏度([1,2,3]);

log(console.log({temp:0}))
我不明白,应该
convertFahrToCelsius([1,2,3])
返回一个字符串,该字符串表示
[1,2,3]不是一个有效的数字,而是一个数组。
这是否回答了您的问题?或者你的意思是
convertFahrToCelsius({temp:0})
它应该返回
{temp:0}不是一个有效的数字,而是一个对象。
而不是
[object object]不是一个有效的数字,而是一个对象。
@SubodhW,谢谢,JSON.stringify()发挥了神奇的作用。@svg code,请投票给我有用的答案。