[英]Cannot Reach Deleted Array Object
我們正在開發一款可顯示員工輪班列表的應用程序。 如果一個班次已經過去,我們想從班次數組中刪除它,因此不將其打印到DOM。
我們正在使用數組的delete
屬性有效地刪除對象。 這樣做,我們知道刪除將使對象保留為undefined
。 然而,當它在屏幕上打印時,出現未定義(這是很有意義的),但是當我們嘗試使用某個功能來抓取它們以解決此問題時(我們將復制沒有未定義的數組),我們可以到達未定義的位置。
我們如何抓住未定義的地方?
HTML :
<ul>
<li ng-repeat="shift in CurrentUser.orderedSchedule = (schedule | orderBy:Time.getSortingDate:false)">
<p>Start time: {{Time.makeDate(shift.start)}}
{{Time.makeTime(shift.start)}}</p>
<p>end time: {{Time.makeDate(shift.end)}}
{{Time.makeTime(shift.end)}}</p>
</li>
</ul>
UserController.js :
$scope.getShifts = function(){
$scope.schedule = $scope.CurrentUser.user.shifts; //array of objects that gets printed on screen
var now = new Date();
for (var indexOfShift in $scope.schedule){ //checks each shift
var start = $scope.schedule[indexOfShift].start; //date object, the start of the shift
if(start instanceof Date){
if(parseInt(start.getTime())-parseInt(now.getTime())<0){
//if the 'future time' has already passed now
//remove the shift
alert(start+" is in the past");
delete $scope.CurrentUser.user.shifts[indexOfShift]; //deleting shift
$scope.schedule = $scope.CurrentUser.user.shifts; //trying to update that we removed it, so we can find undefined
}
}
}
for(var indexOfShift in $scope.schedule){ //looping shifts again to look for undef
console.log($scope.schedule[indexOfShift]); //this prints all of them but the undefines don't appear
if($scope.schedule[indexOfShift].start===undefined){ //we never hit this
alert("found a blank one");
}
}
};
以下是我們的用戶數據隨變化的樣例(對象數組):
$scope.CurrentUser.user = [
{
'name': 'John Smith',
'shifts':[
{'start':new Date(2012, 07, 27, 4, 44),
'end': new Date(2012, 07, 27, 12, 21)
},
{'start':new Date(2014, 09, 09, 20, 02),
'end': new Date(2014, 09, 10, 7, 06)
}
]
}
];
為什么我們達不到定義? 他們去哪了?
for(var i in arr)循環不會遍歷未定義的項目。 兩種解決方案:
for(var i = 0; i <myLength; i ++){//做某事}
在您的情況下使用Splice。
在這種情況下,刪除只會將元素設置為未定義:
myArray = ['a','b','c','d']
刪除myArray [0]
myArray的
結果:[未定義,“ b”,“ c”,“ d”]
Splice實際上從數組中刪除了該元素:
myArray = ['a','b','c','d']
myArray.splice(0,2)
myArray的
結果:[“ c”,“ d”]
有關拼接的更多信息: Microsoft Link
對於來自Mizzila的示例:
var myFish =["angel", "clown", "drum", "mandarin", "surgeon"];
//removes 1 element from index 3
removed = myFish.splice(3, 1);
//myFish is ["angel", "clown", "drum", "surgeon"]
//removed is ["mandarin"]
在您的情況下使用此功能。
//delete $scope.CurrentUser.user.shifts[indexOfShift];
$scope.CurrentUser.user.shifts.splice(indexOfShift, 1);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.