角度计算奇怪的行为

Angular Calculate strange behaviour

本文关键字:计算      更新时间:2023-10-06

我用angular.js计算高度,并将值添加到css样式标记中,这是一个ng重复循环

这一行的计算是错误的:

<div style="height: {{60.0 / 100.0 * (100 - (100.0 / 0.27 * (item.wert + 1.0 - 0.95)))}}%; ">
    <p>{{item.wert}}</p>
</div>

当我将item.wert与因子1相乘时,结果是正确的,所以这是有效的:

<div style="height: {{60.0 / 100.0 * (100 - (100.0 / 0.27 * ((item.wert * 1.0) + 1.0 - 0.95)))}}%; ">
    <p>{{item.wert}}</p>
</div>

有人知道我为什么要把它乘以1吗?谢谢

我认为item.wert是一个字符串而不是int,所以当你做* 1时,它实际上会把它变成int,你可以用它来计算。

item.wert的类型取决于存储在其中的值。例如,以下代码打印string:

$scope.item={};
$scope.item.wert = "";
console.log(typeof($scope.item.wert)) //string;  

但以下代码打印编号:

$scope.item={};
$scope.item.wert = 2;
console.log(typeof($scope.item.wert)) //number;

所以,表达式的结果可能会因存储在item.wert中的值而异。

请看一下MDN的算术运算符文章。

加法(+):

// Number + String -> concatenation
5 + "foo" // "5foo"

减法(-):

 // Number - String -> NaN
    "foo" - 3 // NaN

乘法(*)

// Number * String -> NaN
"foo" * 2 // NaN

希望以上信息能回答您的问题。