javascript - 为什么这个函数返回 NaN?

标签 javascript jquery visual-studio date nan

乍一看,这似乎与许多其他关于 JavaScript 中的 NaN 的问题类似,但我向你保证并非如此。

我有这段代码可以转换从文本框中获取的值,并在单击表单中的按钮后将其转换为日期:

var dateString = $('#itemAcquiredTxt').val(); //Would have a value of '2013-12-15'
var dateAcquired = new Date(dateString); //Invalid Date ?

文本框 itemAcquiredTxt 的值将从数据库调用中获取“2013-12-15”(YYYY-MM-DD 格式):

$('#itemAcquiredTxt').val(new Date(item.DateAcquired).toLocaleDateString());

创建新的 Date 对象后,它显示“无效日期”。

好的...所以我想通过将年、月和日作为数字传递给 Date 对象来制作 Date 对象——它的其他构造函数之一。

 var year = Number(dateString.split("-")[0]); //Returns NaN
 var month = Number(dateString.split("-")[1]); //Returns NaN
 var day = Number(dateString.split("-")[2]); //Returns NaN
 var dateAcquired = new Date(year, month - 1, day); //InvalidDate

我尝试用破折号拆分日期文本框中的字符串,并使用 Number 和 parseInt 将字符串转换为数字 - 但两者都给了我一个 NaN。我仔细检查了字符串值,似乎没有任何错误:拆分项分别为“2013”​​、“12”、“15”。

我对自己说...也许我的代码不好,然后在 JSFiddle 上试了一下 https://jsfiddle.net/jrxg40js/
但是正如您在那里看到的那样,在文本中放置一个日期并按下按钮后,它就起作用了!

这是相关的 HTML 代码

<table id="inputTable">
            <tr>
                <td><span><strong>Name:</strong></span></td>
                <td><input id="itemNameTxt" type="text" value="" /></td>
            </tr>
            <tr>
                <td><span><strong>Category:</strong></span></td>
                <td>
                    <select id="categorySelect" ng-model="selectedCategory" ng-change="changeSubCategoryList(selectedCategory)" ng-options="cat as cat.CategoryName for cat in categoriesObj track by cat.CategoryID">
                        <option value="">---Please Select One---</option>
                    </select>
                </td>
            </tr>
            <tr ng-show="hasSubCat">
                <td><span><strong>Sub Category</strong></span></td>
                <td>
                    <select id="subCategorySelect">
                        <option value="">---Please Select One---</option>
                        <option ng-repeat="sub in subCategoryObj" value="{{sub.SubCatID}}">{{sub.SubCatName}}</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td><span><strong>Description:</strong></span></td>
                <td><input id="itemDescriptionTxt" type="text" value="" /></td>
            </tr>
            <tr>
                <td><span><strong>Serial Number:</strong></span></td>
                <td><input id="itemSerialNumberTxt" type="text" value="" /></td>
            </tr>
            <tr>
                <td><span><strong>Year:</strong></span></td>
                <td><input id="itemYearTxt" type="text" value="" /></td>
            </tr>
            <tr>
                <td><span><strong>Initial Cost:</strong></span></td>
                <td><input id="itemValueTxt" type="text" value="" /></td>
            </tr>
            <tr>
                <td><span><strong>Department:</strong></span></td>
                <td>
                    <select id="departmentSelect">
                        <option value="">---Please Select One---</option>
                        <option ng-repeat="dep in departmentsObj" value="{{dep.RoleID}}">{{dep.RoleDescription}}</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td><span><strong>Campus:</strong></span></td>
                <td>
                    <select id="campusSelect" ng-model="selectedCampus" ng-change="changeBuildingList(selectedCampus)" ng-options="campus as campus.CampusDescription for campus in campusesObj track by campus.CampusID">
                        <option value="">---Please Select One---</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td><span><strong>Building:</strong></span></td>
                <td>
                    <select id="buildingSelect">
                        <option value=""> </option>
                        <option ng-repeat="building in buildingsObj" value="{{building.BuildingID}}">{{building.BuildingDescription}}</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td><span><strong>Date Acquired:</strong></span></td>
                <td><input id="itemAcquiredTxt" type="text" value="" /></td>
            </tr>
            <tr>
                <td><span><strong>Notes:</strong></span></td>
                <td>
                    <textarea id="noteTxt"></textarea>
                </td>
            </tr>
        </table>

用于使用用户键入的新数据更新项目的相关 AngularJS 函数 - 当用户按下确认按钮时调用该函数:

$scope.editItem = function () {
    var dateString = $('#itemAcquiredTxt').val();
    dateAcquired = new Date(dateString);
    var invItem = {
        ItemID: $('#itemID').val(),
        ItemName: $('#itemNameTxt').val().trim(),
        CategoryID: $('#categorySelect').find(":selected").val(),
        SubCategoryID: $('#subCategorySelect').find(":selected").val(),
        Description: $('#itemDescriptionTxt').val().trim(),
        SerialNumber: $('#itemSerialNumberTxt').val().trim(),
        Year: $('#itemYearTxt').val().trim(),
        DateAcquired: dateAcquired,
        Value: $('#itemValueTxt').val().trim(),
        RoleID: $('#departmentSelect').find(":selected").val(),
        Barcode: null,
        Notes: $('#noteTxt').val().trim(),
        Deleted: null,
        AddedBy: null,
        DateAdded: null,
        ModifiedBy: null, //Added by server
        DateModified: null,
        DeletedBy: '',
        DateDeleted: null,
        CampusID: $('#campusSelect').find(":selected").val(),
        BuildingID: $('#buildingSelect').find(":selected").val(),
        RoomID: null
    };
    $http.put("api/inventory/", invItem).success(function (data, status, headers, config) {
        inventoryData.retrieveData(); //On success, refresh zeh data
    }).error(function (data, status, headers, config) {
        console.log(data);
    });

    $("#dialogForm").dialog("close");

为什么我的代码在我的工作环境(IE11 上的 Visual Studio 2015 调试)中返回 NaN 而其他站点(例如 JSFiddle)返回我所期望的?

最佳答案

解决了这个问题——我真的不知道它是什么。

问题只发生在项目更新期间,而不是在添加新项目时 - 所以它必须在我填充元素值时出现。

$('#itemAcquiredTxt').val(new Date(item.DateAcquired).toLocaleDateString());

执行 console.log(item.DateAcquired) 返回字符串“2015-12-15T00:00:00”,.toLocaleDateString() 会将其转换为“2015-12-15 "并解析为 Date 对象。

在尝试将其字符串转换为日期时,编辑该元素的值总是会导致 NaN/InvalidDate。

我的解决方案是...

$('#itemAcquiredTxt').val(item.DateAcquired.split('T')[0]);

根本不使用日期。 现在可以了。

关于javascript - 为什么这个函数返回 NaN?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34292733/

相关文章:

jquery - 使用 jQuery 禁用单选按钮

jquery - 选择下拉列表时从数据库填充文本区域

jquery - 在 ASP.NET MVC Action 链接中使用 JQuery 变量

c++ - std::map 是否需要初始化?

c# - 为 Visual Studio 安装 Hyper-V 模拟器时出错

javascript - PIXI js, Sprite 未显示,没有错误

javascript - Vuefire - 在 v-for 循环中获取 key

javascript - 如何通过在查询中使用值来选中/取消选中复选框

javascript - 添加到 jQuery 选项卡的链接

c# - 创建一个类似 C# 和 XNA 'Monster Dash' 的游戏