我有一个像这样的数组:
var data = [
{
"title" : "Title 1",
"slideText" : "",
"startTime" : 0
},
{
"title" : "Title 2",
"slideText" : "",
"startTime" : 60
},
{
"title" : "Title 3",
"slideText" : "",
"startTime" : 120
}
];
我在HTML5视频上有一个seeked
事件监听器。当用户寻找时,我需要检查它们的位置并确定它们所在阵列中的哪个索引。例如,他们寻求72秒,他们将在阵列[1]
现在我有这个:
player.addEventListener("seeked", function(event)
{
currentTime = player.currentTime;
angular.forEach($scope.data, function(value, key)
{
if (currentTime >= $scope.data[key].startTime && currentTime <= $scope.data[key + 1].startTime)
{
$scope.$apply(function()
{
$scope.setActive(key);
});
}
});
});
这一切都有效,直到所寻找的时间到达数组的末尾并且$scope.data[key + 1].time
未定义。我该怎么做呢?我的思绪现在不在轨道上,我还没有喝咖啡:|
修改
新功能正常工作
player.addEventListener("seeked", function(event)
{
currentTime = player.currentTime;
for (var i = 0; i <= $scope.data.length; i++)
{
if ($scope.data[i + 1] != undefined)
{
if (currentTime < $scope.data[i + 1].startTime)
{
$scope.$apply(function()
{
$scope.setActive(i);
});
break;
}
}
else
{
$scope.$apply(function()
{
$scope.setActive($scope.data.length - 1);
});
}
}
});
答案 0 :(得分:2)
首先测试数组元素的存在。如果失败,其他测试将被忽略:
if ($scope.data[key+1] && currentTime>=$scope.data[key].startTime && currentTime<=$scope.data[key+1].startTime)
答案 1 :(得分:1)
您需要检查[key + 1]
,以确保您不会尝试访问超出数组长度的元素。
player.addEventListener("seeked", function(event)
{
currentTime = player.currentTime;
angular.forEach($scope.data, function(value, key)
{
if ( ($scope.data[key+1] != undefined) && currentTime < $scope.data[key+1].startTime)
{
// this is the one we are after
return false; // exit foreach
} else {
// we are on the last one.
}
});
});
答案 2 :(得分:0)
这是最终的解决方案
player.addEventListener("seeked", function(event)
{
currentTime = player.currentTime;
for (var i = 0; i <= $scope.data.length; i++)
{
if ($scope.data[i + 1] != undefined)
{
if (currentTime < $scope.data[i + 1].startTime)
{
$scope.$apply(function()
{
$scope.setActive(i);
});
break;
}
}
else
{
$scope.$apply(function()
{
$scope.setActive(i - 1);
});
}
}
});