Na początku może to wyglądać jak wiele innych pytań zadanych już na NaN w JavaScript, ale zapewniam cię, że tak nie jest.Dlaczego ta funkcja zwraca NaN?
Mam ten fragment kodu, który konwertuje chwyta wartość z pola tekstowego i zamienia go na randkę po kliknięciu przycisku w postaci:
var dateString = $('#itemAcquiredTxt').val(); //Would have a value of '2013-12-15'
var dateAcquired = new Date(dateString); //Invalid Date ?
Pole tekstowe itemAcquiredTxt miałaby wartość „2013 -12-15" (w formacie RRRR-MM-DD) pochodzi z połączenia bazy danych:
$('#itemAcquiredTxt').val(new Date(item.DateAcquired).toLocaleDateString());
Po utworzeniu nowego obiektu Date to daje mi "Nieprawidłowa data".
OK ... Więc pomyślałem o zrobieniu obiektu Date, przekazując go rok, miesiąc i dzień jako liczby - jeden z jego innych konstruktorów.
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
próbowałem dzielenie ciąg datę tekstowym przez myślnik, i przekonwertować ciąg na liczbę używając zarówno liczby i parseInt - ale oba dał mi Nan. Sprawdziłem dwukrotnie wartości łańcuchów i nic nie wydawało się błędne: odpowiednio "2013", "12", "15" na podzielonych elementach.
powiedziałem sobie ... może mój kod jest zły, i próbowaliśmy go na JSFiddle https://jsfiddle.net/jrxg40js/
Ale jak można tam zobaczyć, po umieszczeniu w tekście datę i naciśnięcie przycisku, to działa!
Herezje odpowiedni kod 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>
Istotne angularjs funkcja służy do aktualizacji elementu z nowymi danymi kluczach przez użytkownika - funkcja jest wywoływana, gdy użytkownik naciśnie przycisk potwierdzający:
$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");
Dlaczego mój kod zwraca NaN w moim środowisku pracy (Visual Studio 2015 debugowanie w IE11), gdy inne witryny, takie jak JSFiddle, zwracają to, czego się spodziewam?
Czy jesteś pewien, że ciąg daty naprawdę jest dokładnie taki, jak myślisz? Czy użyłeś 'console.log()', aby zrzucić go na konsolę, zanim użyjesz go do zrobienia daty lub sprawdzenia za pomocą debugera przeglądarki?Musi być tak, że coś nie dzieje się tak, jak myślisz. Sprawdź wszystkie swoje założenia! – Pointy
Na przykład: czy jesteś pewien, że istnieje tylko jeden '' z tym identyfikatorem na stronie? – Pointy
Całkiem pewne. Sprawdzono zarówno debugger przeglądarki, jak i console.log. I tak, istnieje tylko jedno wejście z tym identyfikatorem. – Cuauhtemoc