JavaScript 转换 - 为什么比较 "5"> "300"返回 true?

标签 javascript casting

在我的应用程序中有两个文本框

 <input type="text" ng-model="priceSlider.min" /><br/>
 <input type="text" ng-model="priceSlider.max" /><br/>

我的 angularjs Controller 是:

app.controller('MainCtrl', function($scope) {
    $scope.priceSlider       = {};
    $scope.priceSlider.min   = 100;
    $scope.priceSlider.max   = 400;
    $scope.priceSlider.ceil  = 500;
    $scope.priceSlider.floor = 0;

    $scope.$watch('priceSlider.min',function(newVal,oldVal) {
        if(isNaN($scope.priceSlider.min)) {
            console.log('naan');
            $scope.priceSlider.min=oldVal;
        }

        if($scope.priceSlider.min>$scope.priceSlider.max) {
            console.log($scope.priceSlider.min>$scope.priceSlider.max);
            console.log($scope.priceSlider.min+":"+$scope.priceSlider.max);

            var t = $scope.priceSlider.min;
            $scope.priceSlider.min = $scope.priceSlider.max;
            $scope.priceSlider.max = t;
        }
    }
});

现在大多数时候 $watch 中的 if 条件工作正常,但在某些情况下会失败,例如:如果我在两个文本框中写下 200 和 300,然后选择第一个文本框并尝试更改(到 5) ,如果值为 5 和 300,但条件 5>300 如果显示 true... 我无法找到为什么会发生这种情况。我是不是做了什么蠢事

请检查plunker中的东西。

http://plnkr.co/edit/4Wga7zCIX2udPZa6b0gI

最佳答案

比较 5 和 300 时结果为 true 的原因可能是它正在进行字符串比较。

"5" > "300" 
>> true

因此将值转换为整数然后进行比较。使用 parseInt(val, 10)Number(val)

关于JavaScript 转换 - 为什么比较 "5"> "300"返回 true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32005885/

相关文章:

javascript - JQuery 选择器多类对象

c# - 实现经过身份验证的用户更新状态作为对系统状态更改的 react 的最佳方法。 (ASP.NET MVC 网站)

java - 如何仅使用强制转换来显示数字的前 2 位小数?

java - Struts2 INPUT 结果 : how does it work? 如何处理转换/验证错误?

javascript - 我可以在 javascript 中创建一个函数来绕过递归代码吗?

javascript - React 不渲染 css 样式

javascript - 在 Protractor 中加载页面之前单击对话框

c# - VB 编译器不隐式转换为对象?

python - 在 Haskell 中以通用方式导航 JSON 对象

c++ - C++ 中的删除运算符是否需要正确的类型?