JavaScript更改元素并将其打印在不同的行中

时间:2016-12-24 18:08:58

标签: javascript arrays element

我有这个代码来查找匹配的名称并将其更改为其他名称。 但是他们每次都在同一条线上改变。

var names1 = ["Rui", "Jose", "Carlos", "Miguel"];

var names2 = ["Rui", "Tiago", "Jose", "Carlos", "Rogerio"];

for (var i = 0; i < names1.length; i++) {
  for (var j = 0; j < names2.length; j++) {

    if (names1[i] == names2[j]) {

      names2[j] = "Maria", "Fred";

    }

  }
}

console.log(names2);

我想知道如何以不同的方式打印它们。 因为它显示如下:

MariaFred

蒂亚戈

MariaFred

MariaFred

罗热

我想要:

超群,

佛瑞德,

蒂亚戈,

罗热。

你能帮助我吗?

4 个答案:

答案 0 :(得分:0)

而不是

console.log(names2)

试试这个

for (var i = 0; i < names2.length; i++) {
console.log(names2[i]);

}

答案 1 :(得分:0)

试试这个:

var names1 = ["Rui", "Jose", "Carlos", "Miguel"];
var names2 = ["Rui", "Tiago", "Jose", "Carlos", "Rogerio"];
var matchFound = false;
for (var i = 0; i < names1.length; i++) {
  for (var j = 0; j < names2.length; j++) {
    if (names1[i] == names2[j] && matchFound === false) {
      // when the name matches, print Maria and Fred in 2 different lines
      console.log("Maria,");
      console.log("Fred,");
      matchFound  = true;
    } else { // if name doesn't match, just print the element from 2nd array
       console.log(names2[j]");
    }

  }
}

答案 2 :(得分:0)

如果找到匹配的名称,您可以使用数组作为excahnge名称,并使用索引插入更改的名称。

var names1 = ["Rui", "Jose", "Carlos", "Miguel"],
    names2 = ["Rui", "Tiago", "Jose", "Carlos", "Rogerio"],
    matched = ["Maria", "Fred"],
    index = 0,
    i, j;

outer: for (j = 0; j < names2.length; j++) {
    for (i = 0; i < names1.length; i++) {
        if (names1[i] == names2[j]) {
            names2[j] = matched[index++];
            index %= matched.length;
            continue outer;
        }
    }
}

console.log(names2);

为了加快检查速度,您可以使用哈希表并对其进行检查。

var names1 = ["Rui", "Jose", "Carlos", "Miguel"],
    names2 = ["Rui", "Tiago", "Jose", "Carlos", "Rogerio"],
    matched = ["Maria", "Fred"],
    index = 0,
    hash = Object.create(null);

names1.forEach(function (a) {
    hash[a] = true;
});

names2.forEach(function (a, i, aa) {
    if (hash[a]) {
        aa[i] = matched[index++];
        index %= matched.length;
    }
});

console.log(names2);

答案 3 :(得分:0)

在下面的例子中,我认为应该从某些来源中选择随机名称

var names1 = ["Rui", "Jose", "Carlos", "Miguel"];
var names2 = ["Rui", "Tiago", "Jose", "Carlos", "Rogerio"];
var random_names = ['Maria', 'Fred', 'Someother']
var random_names_counter = 0;
for (var i = 0; i < names1.length; i++) {
    for (var j = 0; j < names2.length; j++) {
        if (names1[i] == names2[j]) {
            names2[j] = random_names[random_names_counter++];
        }
    }
}

console.log(names2);