微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用javascript同时迭代两个字符串数组

如何解决使用javascript同时迭代两个字符串数组

我是javascript新手。现在,我想通过同时迭代两个字符串数组来比较两个网站对。这两个字符串数组的长度相同。我已经搜索了网站,但没有找到使用javascript的方法。例如,在python中,人们可以通过使用zip()来实现此目的, How to merge lists into a list of tuples?

但是,在javascript中,我尝试执行类似的操作,但是每次迭代第一个列表的元素时,它都会在第二个列表上进行迭代,这是我不想要的。

代码与我期望的不符

var FistList=['https://test1-1/travel','https://test1-1/cook','https://test1-1/eat'];
var SecondList=['https://test1-2/travel','https://test1-2/cook','https://test1-2/eat'];

 FirstList.forEach(firstListItem => {
            SecondList.forEach(secondListItem => {
                //do comparison for these two websites....
            });
        });

我希望是一对一对地进行比较,这是=>

first loop: do comparison of 'https://test1-1/travel' and 'https://test1-2/travel'
second loop: do comparison of 'https://test1-1/cook' and 'https://test1-2/cook'
third loop: do comparison of 'https://test1-1/eat' and 'https://test1-2/eat'

搜索了一整天,但无法在javascript中找到方法。请指教。预先感谢!

解决方法

如果要比较每个数组在相同位置的值,只需使用forEach的index参数引用其他数组中的数组元素

var FirstList=['https://test1-1/travel','https://test1-1/cook','https://test1-1/eat'];
var SecondList=['https://test1-2/travel','https://test1-1/eat'];

FirstList.forEach((str,i) => console.log(str === SecondList[i]))

,

我认为forEach循环的目的是仅迭代1个列表。我会考虑使用通用的for循环来实现此目的。

编辑:我编辑了代码,并添加了一个字符串原型函数来计算2个字符串之间的Levenstein距离。在示例中更改了字符串的确切位置检测更改是否严格并不十分严格。但是我希望这些示例可能仍然不能完全反映您的真实数据,因此,我给您的是Levenstein,而不是给您一些可疑的正则表达式,并希望您了解它并不关心差异在哪里,它只是在乎多少已经改变。在此示例中,我只允许使用1个字符或更少的字符差:if (diff <= 1) {

//Define a string function for Levenstein Edit Distance
//call it "distancefrom" for clarity
String.prototype.distancefrom = function(string) {
    var a = this,b = string + "",m = [],i,j,min = Math.min;
    if (!(a && b)) return (b || a).length;
    for (i = 0; i <= b.length; m[i] = [i++]);
    for (j = 0; j <= a.length; m[0][j] = j++);

    for (i = 1; i <= b.length; i++) {
        for (j = 1; j <= a.length; j++) {
            m[i][j] = b.charAt(i - 1) == a.charAt(j - 1)
                ? m[i - 1][j - 1]
                : m[i][j] = min(
                    m[i - 1][j - 1] + 1,min(m[i][j - 1] + 1,m[i - 1 ][j] + 1))
        }
    }

    return m[b.length][a.length];
}


//Your Code
var FirstList=['https://test1-1/travel','https://test1-1/eat','https://waffles.domain/syrup','http://pancakes.webpresence/butter'];
var SecondList=['https://test1-2/travel','https://test1-2/cook','https://test1-2/eat','https://waffles.domain/syrups','https://pancakes.webpresence/buttery'];

for (let i=0; i < FirstList.length; i++) {
  let diff = FirstList[i].distancefrom(SecondList[i]);
  console.log('"'+FirstList[i]+'" is different than "'+SecondList[i]+'" by '+diff+' characters');
  if (diff <= 1) {
    console.log('Since its less than 1 character of difference,it would technically Pass our test.');
  } else {
    console.log('Since its more than 1 character of difference,it would Fail our test!');
  }
  console.log('-----------------');
}

参考: Levenstin Gist by scottgelin on GitHub

,

我认为这里已经回答了一个非常类似的问题:How to compare arrays in JavaScript?

可接受的答案(https://stackoverflow.com/a/14853974/1842205)深入描述了如何实现这一目标。

JavaScript缺少像Python中提到的zip()方法那样的功能。但是我们在JS中有类似原型的东西:)。然后您可以创建2D数组,如下所示:

function createArray(length) {
    var arr = new Array(length || 0),i = length;

    if (arguments.length > 1) {
       var args = Array.prototype.slice.call(arguments,1);
       while(i--) arr[length-1 - i] = createArray.apply(this,args);
    }

    return arr;
}

Array.prototype.zip = function (secondArr) {
   let result = createArray(secondArr.length,2);

   for (let i = 0; i < this.length; i++) {
      result[i][0] = this[i];
      result[i][1] = secondArr[i];
   }

   return result;
};

// usage
var FistList=['https://test1-1/travel','https://test1-2/eat'];

console.log(JSON.stringify(FistList.zip(SecondList)));
,

我喜欢OP的使用zip(can be home-rolled或从loadashunderscore重新使用的zip)提供功能更强大的解决方案的想法。

const firstArray=['https://test1-1/travel','https://test1-1/eat'];
const secondArray=['https://test1-2/travel','https://test1-2/eat'];

const zipped = _.zip(firstArray,secondArray)
const compared = zipped.map(([first,second]) => first === second)

console.log(compared)

// reduce the pairwise comparison to a single bool with every()
// depends on requirements,but probably true iff every comparison is true

const arraysMatch = compared.every(e => e)
console.log(arraysMatch)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>

请注意,更多的功能性解决方案通常涉及创建一些中间数组(又称垃圾),这对于较小的输入是很好的选择。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。