如何在数组b中找到第[i]个元素

时间:2018-03-10 05:01:18

标签: javascript arrays loops

我试图在数组日,时间,srcdes中显示位于第(i)个索引的单词 但输出正在扭曲。我得到了我预期的输出但是在两个数组元素之间有3个非必需元素被生成,例如

输出

Sunday-9-Dombivli-DombivliMonday-10-Thane-ThaneWednesday-12-Vikhroli-VikhroliSunday-9-Dombivli-Dombivli

这里“-9-Dombivli-DombivliMonday”不是必需的。在星期日之后,应该直接生成10个例如。

预期输出

Sunday-10-vikhroli-dombivli

var days = 
 ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];  
var time = ["9", "10","11","12","1","2","3"];  
var srcdes = ["Dombivli", "Thane","Mulund","Vikhroli","Ghatkopar","Sion","Dadar"];  
var a = [0,2,3,0]
for (var i = 0; i < a.length; i++) {
 z = a[i]
document.write(days[z]+"-"+time[z] +"-" + srcdes[z] +"-"+ srcdes[z] )
 }
我在做错了什么?谢谢你的建议

2 个答案:

答案 0 :(得分:0)

var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]; 
var time = ["9", "10","11","12","1","2","3"]; 
var srcdes = ["Dombivli","Thane","Mulund","Vikhroli","Ghatkopar","Sion","Dadar"]; 
var a = [0,2,3,0]
document.write(days[a[0]]+"-"+time[a[1]] +"-" + srcdes[a[2]] +"-"+ srcdes[a[3]] ) 

不需要循环,

答案 1 :(得分:-1)

您正尝试在所有阵列中使用相同的索引(a [i])。相反,您可以跳过for循环并直接访问索引值,如下所示。

var a = [0,2,3,0]
document.write(days[a[0]]+"-"+time[a[1]] +"-" + srcdes[a[2]] +"-"+ srcdes[a[3]] )

或者,您可以根据需要编写条件选择,如下所示。

var a = [0,2,3,0]
for (var i = 0; i < a.length-3; i++) {
    document.write(days[a[i]]+"-"+time[a[i+1]] +"-" + srcdes[a[i+2]] +"-"+ srcdes[a[i+3]] )
}