将一个数组中的数字与另一个数组Javascript的索引进行比较

时间:2017-02-14 21:44:06

标签: javascript arrays indexing elements

只是想知道是否可以做到这样的事情以及如何完成。我的目标是从一个数组中获取所有数字并将它们与另一个数组的索引进行比较,最后打印元素。

示例:

var myindex = new Array(2, 0);

var array1 = new Array("text", "apple", "sample")
var array2 = new array("book", "phone", "orange")

myindex.forEach(number => document.write(array1.indexOf(number)))

预期结果:将打印以下内容:样本橙色教科书

第一个问题:显示的所有内容都是-1错误,这意味着我认为:数组中没有数字,但有一个数字,所以我不明白? 第二个问题:我还需要实现array2与array1一起工作,这样我们才能真正看到如上所示的预期结果。我将不胜感激任何帮助

5 个答案:

答案 0 :(得分:0)

您可以简单地遍历索引数组,然后使用它的值:

var myIndex = [2,0];
var array1 = new Array("text", "apple", "sample");
 var array2 = new Array("book", "phone", "orange");

for (var i = 0; i < myIndex.length; i++){
  console.log(array1[myIndex[i]] + " " + array2[myIndex[i]]);
}

答案 1 :(得分:0)

您可以使用数组作为数据,并检查给定索引处的数据是否存在。然后输出。

var myindex = [2, 0],
    array = [["text", "apple", "sample"], ["book", "phone", "orange"]];

myindex.forEach(number => array[number] && console.log(array[number]));

答案 2 :(得分:0)

此处不需要indexOf,它会搜索数组。您需要通过索引(方括号表示法)访问数组以获取值:

var myindex = new Array(2, 0);

var array1 = new Array("text", "apple", "sample")
var array2 = new Array("book", "phone", "orange")

myindex.forEach(number => console.log(array1[number], array2[number]));

注意:数组构造函数中有拼写错误:它必须是Array(),而不是array()。其次,请勿使用document.write

答案 3 :(得分:0)

您只需要使用array[index]语法访问数组元素。

var myIndexs = [2, 0];

var array1 = ["text", "apple", "sample", "book"];
var array2 = ["book", "phone", "orange", "text"];

myIndexs.forEach((index) => document.write(`${array1[index]} ${array2[index]} `));

另外,使用[]语法创建数组,而不是Array()https://coderwall.com/p/h4xm0w/why-never-use-new-array-in-javascript

如果你想把结果分成两行,那么它有点取决于你的用例,你真的想写入html,你可以这样做:

var myIndexs = [2, 0];

var array1 = ["text", "apple", "sample", "book"];
var array2 = ["book", "phone", "orange", "text"];

const results1 = [];
const results2 = [];

myIndexs.forEach((index) => {
  // Here you might want to validate if array1[index] exists
  results1.push(array1[index]);

  // Here you might want to validate if array2[index] exists
  results2.push(array2[index]);
});

document.write(`${results1}<br />${results2}`);

但是,它可能取决于您的用例。我可能想在html中创建两个不同的节点目标,并将每个结果写入不同的目标。您可能只需要javascript中的两个数组变量。你不应该盲目地遵循任何代码,你应该适应你的具体用例。

答案 4 :(得分:0)

只是为了一些变化和乐趣,你可以这样做;

var myIndex = new Array(2, 0),
     array1 = new Array("text", "apple", "sample"),
     array2 = new Array("book", "phone", "orange");
console.log.apply(console, myIndex.reduce((p,c) => p.concat(array1[c],array2[c]),[]));

相关问题