我有一个值为var arr = [["imagelink1","0","20"],["imagelink2","21","50"],["imagelink3","51","100"],["imagelink4","101","200"],[null]];
我从csv获取此数组,我无法修改 第一个是图像链接第二个元素是开始时间,第三个元素是结束时间。我需要调用一个时间值为显示的函数,该函数将检查它落入的时间范围并返回图像链接。
function displayimage(timval){ Code here }
调用功能displayimage(22);应检查数组并返回imagelink2。什么可能是最优化的解决方案?
答案 0 :(得分:0)
您可以使用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))
&#13;
答案 1 :(得分:0)
一个简单的循环应该是有效的:
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
&#13;
答案 2 :(得分:0)
使用常规和快速 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));
&#13;
答案 3 :(得分:0)
希望这对你有用
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>