【问题标题】:Get key value of first item in object获取对象中第一项的键值
【发布时间】:2018-12-19 04:10:48
【问题描述】:

我有以下定义段落的结束和开始时间的对象:

var times = {
 "p1": [24.500, 29.268],
 "p2": [29.268, 29.441],
 "p3": [29.441, 29.640]
};

我想在段落更改时致电updateCurrentParagraph

vid.addEventListener("timeupdate", function() {

    var t = this.currentTime;
    for (var key in times) {
       if (t >= times[key][0] && t < times[key][1])
       {
           updateCurrentParagraph(key);
           return;
       }
    }

    // at end of audio
    if (times[times.length-1][1] == t){
        updateCurrentParagraph(???);
        return;
    }

    updateCurrentParagraph("unknown");
    return;

});

我在??? 做什么才能获得“p3”?

【问题讨论】:

  • Object.keys(times)[0]??
  • 什么是first_paragraph
  • 你的问题一点都不清楚。
  • 首先需要在分配前定义first_paragraph,然后添加times.p1=first_paragraph
  • 更新了问题以使其清楚。

标签: javascript


【解决方案1】:

只需使用Object.keys 方法,将您的对象作为参数

var key = Object.keys(times)[0];
var values = times[key]

【讨论】:

  • 我不认为这是可靠的,因为对象中的键不保证顺序。
  • @Mihai Alexandru-Ionut 最后一个键是 Object.keys(times[times.length-1]) 吗?我已经更新了我的问题。
  • 不,因为最后一个键是:var lastKey = Object.keys(times)[times.length-1]
【解决方案2】:

如果属性没有排序,你可以保存最后一个有合适时间在循环后检查的键。

vid.addEventListener("timeupdate", function () {
    var t = this.currentTime,
        last;
    for (var key in times) {
        if (times[key][0] >= t && times[key][1] < t) {
            updateCurrentParagraph(key);
            return;
        }
        if (times[key][1] === t) {
            last = key;
        }
    }

    // at end of audio
    if (last) {
        updateCurrentParagraph(last);
        return;
    }

    updateCurrentParagraph("unknown");
    return;
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-07
    • 2012-09-12
    • 1970-01-01
    • 2017-08-03
    • 2019-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多