我想知道當我們加、減或乘兩個數字串時,幕后會發生什么。這是一個例子:
let strNum1 = "300";
let strNum2 = "22";
let multiply = function(num1, num2) {
let product = num1 * num2;
return `${product}`
};
multiply(strNum1, strNum2); //this will return ==> "6600"
JS 引擎是否首先將這些轉換為整數然后執行操作,或者它是否“神奇地”知道它們是數字,即使它是字串形式?我問的原因是因為long multiplication algorithm。對于大于 8 個字符的數字,與運算子相乘與使用演算法相乘時會變得很時髦。
順便說一句,這是一個leetcode 問題。
uj5u.com熱心網友回復:
您可以在操作之前和之后決議您的值:
let multiply = function(num1 = '', num2 = '') {
const product = Number(num1) * Number(num2);
return `${product}` // Or String(product)
};
uj5u.com熱心網友回復:
回答您的問題:JS 引擎在進行算術運算之前將這些字串轉換為整數。它被稱為Implicit coercion。
你可以在你不知道的 JS 章節中閱讀更多相關資訊。
uj5u.com熱心網友回復:
在加法 ( ) 的情況下,當一個數字被添加到一個字串中時,JavaScript 在連接之前將該數字轉換為一個字串,但在其他算術運算的情況下,如*, -,/JS 引擎會隱式地將字串轉換為整數。
演示:
let result;
// numeric string used with gives string type
result = '3' '2';
console.log(result, typeof result) // "32", "string"
// numeric string used with - , / , * results number type
result = '3' * '2';
console.log(result, typeof result) // 6, "number"
result = '3' - '2';
console.log(result, typeof result) // 1, "number"
result = '3' / '2';
console.log(result, typeof result) // 1.5, "number"
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/490389.html
標籤:javascript 细绳 数学
上一篇:如何根據角色的旋轉移動角色?
