如何检测是否从 parseInt(localStorageService.get('xxx'))返回值;

How can I detect if the return value from parseInt(localStorageService.get('xxx')); is NaN?

本文关键字:get 返回值 localStorageService xxx 何检测 检测 是否 parseInt      更新时间:2023-09-26

我有这个代码:

        getPageTypes: function ($scope) {
            $scope.option.pageTypes = [
                { id: 0, type: 'Edit Basic' },
                { id: 1, type: 'Edit Standard' },
                { id: 2, type: 'Report' }
            ];
            $scope.option.selectedPageType = parseInt(localStorageService.get('xxx'));
        },
如果本地存储

中没有存储"abcd"的条目,如何将 $scope.option.selectedPageType 设置为值 0?

您可以使用

此速记方法来初始化选定的PageType变量:

$scope.option.selectedPageType = parseInt(localStorageService.get('xxx')) || 0;

小心使用原生的isNaN方法,因为MDN文档指出它是一个损坏的函数。例如,对于非数字值(如未定义),它将返回 true。

如果你有可用的 Underscore.js Javascript 库,你也可以考虑使用 _.isNaN

查看isNaN()函数

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN