简体   繁体   中英

Return a word from a words array when the time is the one from the time array. Javascript - React

I am building a transcription service for audio or video file with React.

The backend is done and I'm getting those 2 arrays:

I have an array of time, in second:

const timing = [0, 0.2, 0.8, 0.9, 1.3, 2]

I also have an array of words:

const words = ["hello", "world", "I", "am", "John", "Smith"]

I want to highlight a word only when the timing is right.

Is there any other way than infinity of "if" statement?

if(time = timing[0]) {return words[0]}
if(time = timing[1]) {return words[1]}
...
if(time = timing[n]) {return words[n]}

(*time is equal the the video / audio player)

Thanks!

It would be easier if you use dict and setInterval

 const words = { 0: "hello", 200: "world", 800: "I", 900: "am", 1300: "John", 2000: "Smith" } function speak(timing) { if(timing in words) { console.log(words[timing]) } } current_timestamp = 0 function timer() { speak(current_timestamp) current_timestamp += 100 } setInterval(timer, 100);

 const timing = [0, 0.2, 0.8, 0.9, 1.3, 2]; const words = ['hello', 'world', 'I', 'am', 'John', 'Smith']; function getWord(timing, words, time) { return words[timing.indexOf(time)]; } console.log(getWord(timing, words, 0.9));

I think you could do this:

 const timing = [0, 0.2, 0.8, 0.9, 1.3, 2] const words = ["hello", "world", "I", "am", "John", "Smith"]; var hashTable = {} timing.forEach((i, index)=>{ hashTable[i] = words[index]; }); console.log(hashTable) console.log(hashTable[timing[3]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM