对于具有2个解析数组的循环

时间:2015-10-04 18:03:34

标签: javascript arrays node.js

我有2个阵列

var a = [
    "4",
    "@",
    "/\\",
    "/-\\",
    "^",
    "∂",
    "λ",
    "α",
    "(!",
    "Z",
    "α"
];
var r = [
    "1²",
    "2",
    "?",
    "P\\",
    "[\"/_",
    "l\"/_",
    "|-",
    "|2",
    "|?",
    "®",
    "12",
    "/2",
    "I2",
    "|^",
    "|~",
    "(r)",
    "|`",
    "l2",
    "Я",
    "ʁ",
    "я"
];

我需要解析为1 for statement两个数组

这就是我所拥有的:

for (var index_a=0, index_r=0; index_a < a.length, index_r < r.length ; ++index_a, ++index_r ) {
    new_a = a[index_a];
    console.log(new_a);
    new_r = r[index_r];
    console.log(new_r);
};

输出:

the element from A array: 4
the element from R array: 1²
the element from A array: @
the element from R array: 2
the element from A array: /\
the element from R array: ?
the element from A array: /-\
the element from R array: P\
the element from A array: ^
the element from R array: ["/_
the element from A array: ∂
the element from R array: l"/_
the element from A array: λ
the element from R array: |-
the element from A array: α
the element from R array: |2
the element from A array: (!
the element from R array: |?
the element from A array: Z
the element from R array: ®
the element from A array: α
the element from R array: 12
the element from A array: undefined
the element from R array: /2
the element from A array: undefined
the element from R array: I2
the element from A array: undefined
the element from R array: |^
the element from A array: undefined
the element from R array: |~
the element from A array: undefined
the element from R array: (r)
the element from A array: undefined
the element from R array: |`
the element from A array: undefined
the element from R array: l2
the element from A array: undefined
the element from R array: Я
the element from A array: undefined
the element from R array: ʁ
the element from A array: undefined
the element from R array: я

问题是一个数组比另一个数组长,并且在完成解析最短的数组后,它继续最长的数组,但最短的数组的值是未定义的。当最短的数组结束时,我需要保存最后一个值。我怎样才能做到这一点。 谢谢。

2 个答案:

答案 0 :(得分:0)

检查您尝试从短数组中引用的值。如果未定义,请从短数组中的最后一项获取值。 ?:运算符可以检查此

这样的事情: new_a = a [index_a] =='undefined'?a [a.length-1]:a [index_a];

答案 1 :(得分:0)

我确定可以有1001个实际上非常有趣的答案如何做到这一点,但鉴于您已经在上面展示过的设置,最简单的方法就是环绕:

if(index_a < a.length){
  new_a = a[index_a];
  console.log(new_a);
}

现在,如果你有5个数组需要这样做,那么用一个语句来强制每个数组都会变得很麻烦。一种更有趣的方式是开始考虑另一种方法,如果它存在则返回数组的第n个元素,如果它不存在则没有任何内容。这样你可以忽略返回值,如果它什么都没有,但如果它存在则使用它。

如果有问题的所有阵列都没有回复,那么你就完成了。

有点简单,因为会有一些边缘情况需要考虑才有意思,但这可能是一个很好的方式来开始学习更多关于这些边缘情况,甚至抛出和捕获异常。

完成这项任务的方法很多。