如何按顺序遍历数组,其中序列存储为另一个数组

时间:2013-11-09 11:46:39

标签: javascript arrays loops sequence

以下是这个想法:

var alphabet = ["A","B","C","D","E","F","G","H","I","J","K"]; 
var sequence1 = ["[i]","[i+2]","[i+2]","[i+1]","[i+4]"];

所以基本上我想使用序列'sequence1'迭代'alphabet',这样返回的内容就是:A, C, E, F, J.

我将拥有许多不同的序列,因此有必要将它们分别存储为自己的数组。

2 个答案:

答案 0 :(得分:0)

您可以将序列存储为整数,然后迭代alphabet,例如:

var alphabet  = ["A", "B", "C", ...];
var sequence1 = [0, 2, 2, 1, 4];

for (var i = 0; i < sequence1.length; i++) {
   alphabet[sequence1[i]+i];
}

请注意,最终输出为A, C, E, F, J。序列应为0, 1, 2, 2, 3,因为数组从索引0开始,而不是索引1。

答案 1 :(得分:0)

您似乎正在使用sequence1来描述如何从输出序列中的一个术语跳到下一个术语,所以尝试这样的事情:

var alphabet = ["A","B","C","D","E","F","G","H","I","J","K"],
    sequence1 = [0,2,2,1,4],
    pos = 0,
    newSeq = [];

for (var i = 0, l = sequence1.length; i < l; i++) {
    pos += sequence1[i];

    if (alphabet[pos] !== undefined) {newSeq.push(alphabet[pos]);}
}

将产生一个应该是你想要的数组newSeq

演示:http://jsfiddle.net/BYossarian/uSmg5/