简体   繁体   English

比较两个JS arrays的内容

[英]Comparing the contents of two JS arrays

Trying to compare to arrays in JavaScript with the following approach.尝试使用以下方法与 JavaScript 中的 arrays 进行比较。

 return stack1.forEach((v, i) => v === stack2[i]);

I want to get it working but it is returning undefined instead of true or false if the arrays are the same.我想让它工作,但如果 arrays 相同,它会返回 undefined 而不是 true 或 false。

Here is the full code:这是完整的代码:

const backspace_compare = function(str1, str2) {
  let stack1 = [];
  let stack2 = [];
  for (let i = 0; i < str1.length; i++) {
    str1[i] === "#" ? stack1.pop() : stack1.push(str1[i]);
  }
  for (let i = 0; i < str1.length; i++) {
    str2[i] === "#" ? stack2.pop() : stack2.push(str2[i]);
  }
  return stack1.forEach((v, i) => v === stack2[i]);
};

Any help to fix the way I'm comparing the arrays using a similar approach would be really appreciated.任何帮助解决我使用类似方法比较 arrays 的方式将不胜感激。

Here are some methods I use to compare two array in JS.以下是我用来比较 JS 中的两个数组的一些方法。 The method I prefer usually is JSON.stringify .我通常喜欢的方法是JSON.stringify

However, I feel that your method is the fastest one, just you've to use .every() in place of forEach() .但是,我觉得您的方法是最快的方法,只是您必须使用.every()代替forEach()

 let stack1 = [1, 2, 3, 4]; let stack2 = [1, 2, 3, 4]; console.log('every compare:', stack1.every((v, i) => v === stack2[i])); // or console.log('toString compare:', stack1.toString() === stack2.toString()); // or console.log('JSON compare:', JSON.stringify(stack1) === JSON.stringify(stack2)); // or console.log('short compare:', stack1+'' === stack2+'');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM