繁星coding
2023-08-24 15:36:18
我正在嘗試用js進行簡單的操作。這是我的代碼:var propriedade = process.argv[2]; var a = process.argv[3]; var b = process.argv[4];var result = 0;switch(propriedade) { case "sum": result = a + b; break; case "minus": result = a - b; break;} console.log(result);在終端中,結果不是總和。怎么了?
1 回答

慕尼黑8549860
TA貢獻1818條經驗 獲得超11個贊
下次請解釋一下你得到的結果。
事實上,當您使用 時process.argv[i],您得到的結果是一個字符串:
console.log(
{
typeA: typeof a,
typeB: typeof b
}
);
輸出
{
typeA: 'string',
typeB: 'string'
}
如您所知,String + String是連接,因此如果您傳遞“12”和“45”示例,它將返回“1245”而不是 57。
為此,您應該使用以下方法將字符串轉換為數字(適用于整數或浮點數):
let a = Number(process.argv[3]);
let b = Number(process.argv[4]);
現在效果很好?。?!
[編輯]
在 javascript 中,如果您使用“*”、“/”或“-”等運算符(“+”除外),則字符串將轉換為數字。
let a = "5";
let b = "2";
console.log({
sum: a + b,
minus: a - b,
multiplication: a * b,
devide: a / b
});
//OUTPUT: { sum: '52', minus: 3, multiplication: 10, devide: 2.5 }
添加回答
舉報
0/150
提交
取消