1

我有一个像这样的数组:

var data = [
    {
        "title" : "Title 1",
        "slideText" : "",
        "startTime" : 0
    },
    {
        "title" : "Title 2",
        "slideText" : "",
        "startTime" : 60
    },
    {
        "title" : "Title 3",
        "slideText" : "",
        "startTime" : 120
    }
];

seeked在 HTML5 视频上有一个事件监听器。当用户寻找时,我需要检查他们在哪里,并确定他们在数组中的哪个索引。例如,他们寻求 72 秒,他们将在 array[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);
            });
        }
    }
}); 
4

3 回答 3

2

首先测试数组元素的存在。如果失败,其他测试将被忽略:

if ($scope.data[key+1] && currentTime>=$scope.data[key].startTime && currentTime<=$scope.data[key+1].startTime)
于 2013-03-15T17:31:06.733 回答
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.
        }
    });
});
于 2013-03-15T17:48:39.040 回答
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);
            });
        }
    }
}); 
于 2013-03-15T19:43:15.500 回答