簡體   English   中英

根據時間從JavaScript中的數組更改圖像

[英]Change image based on time from array in javascript

我有一個值var arr = [["imagelink1","0","20"],["imagelink2","21","50"],["imagelink3","51","100"],["imagelink4","101","200"],[null]];

我從無法修改的csv獲取此數組。
第一個是圖像鏈接,第二個元素是開始時間,第三個元素是結束時間。 我需要調用一個帶有時間值的函數,例如display ,它將檢查它屬於哪個時間范圍並返回圖像鏈接。

function displayimage(timval){  Code here }

調用函數displayimage(22); 應該檢查數組並返回imagelink2。 什么是最優化的解決方案?

您可以使用find()來查找timval在第一個元素和第二個元素之間的子數組。

 var arr = [["imagelink1","0","20"],["imagelink2","21","50"],["imagelink3","51","100"],["imagelink4","101","200"],[null]]; function displayimage(timval){ var image = arr.find(e => timval >= e[1] && timval <= e[2]) return image ? image[0] : 'There is no image'; } console.log(displayimage(22)) console.log(displayimage(1000)) 

一個簡單的循環應該很有效:

 var arr = [["imagelink1","0","20"],["imagelink2","21","50"],["imagelink3","51","100"],["imagelink4","101","200"],[null]]; function displayimage(timval){ for (var i = 0; i < arr.length; i++) if (timval >= arr[i][1] && timval <= arr[i][2]) return arr[i][0]; return null; // return whatever default value applies for no match } console.log(displayimage(22)); // imagelink2 console.log(displayimage(222)); // null 

使用常規和快速 for循環的解決方案:

 /** * Gets an image link if the time value is within a limits * * @param timeValue * @param arr input array * @returns {string} */ function displayImage(timeValue, arr) { timeValue = Number(timeValue); // casting to number var imgLink = ""; for (var i = 0, len = arr.length; i < len; i++) { if (arr[i].length === 3 // if it's a valid nested array(of needed length) && (Number(arr[i][1]) <= timeValue && timeValue <= Number(arr[i][2]))) { imgLink = arr[i][0]; break; // avoiding redundant iterations } } return imgLink; } var arr = [["imagelink1","0","20"],["imagelink2","21","50"],["imagelink3","51","100"],["imagelink4","101","200"],[null]]; console.log(displayImage("22", arr)); 

希望這對你有用

 var arr = [["imagelink1","0","2000"],["imagelink2","21","5000"],["imagelink3","51","10000"],["imagelink4","101","20000"],[null]]; displayimage(); function displayimage(){ for (var i = 0; i < arr.length; i++){ if(arr[i].length > 0){ var image = arr[i][0]; setTimeout(function(image){ $(".img").html(image); },arr[i][2],image); } } } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div class="img"> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM