typescript 如何比较两个包含不同数据类型元素的数组?

yhived7q  于 2023-03-09  发布在  TypeScript
关注(0)|答案(3)|浏览(167)

我想检查下面的两个数组是否相同或在typescript中不一样。如果条件失败,按照下面的代码。请让我知道如何解决这个问题:

let props:(string|boolean)[]=['abc','def',true,false,'xyz']
let propsCopied:(string|boolean)[]=['abc','def',true,false,'xyz']
let allPropsCopied:boolean;

if(props===propsCopied){
allPropsCopied=true;
}
myss37ts

myss37ts1#

你可以用这个简短的方法:

JSON.stringify(props)===JSON.stringify(propsCopied)

或采用更完善的方式:

function isArrayEqual(a:(string|boolean)[], b:(string|boolean)[]) {
  if (a === b) return true;
  if (a == null || b == null) return false;
  if (a.length !== b.length) return false;

  // If you don't care about the order of the elements inside
  // the array, you should sort both arrays here.
  // Please note that calling sort on an array will modify that array.
  // you might want to clone your array first.

  for (var i = 0; i < a.length; ++i) {
    if (a[i] !== b[i]) return false;
  }
  return true;
}
h79rfbju

h79rfbju2#

链接问题中答案的 typescript 版本:

function arraysEqual<T>(a: T[] | null, b: T[] | null): bool {
  if (a === b) {
    return true;
  }
  if (a == null || b == null || a.length !== b.length) {
    return false;
  }

  // If you don't care about the order of the elements inside
  // This is not strict. Need to count the number of every elements if need strict.
  // return a.every(i => b.some(i)) && b.every(i => a.some(i));
 

  for (let i = 0; i < a.length; ++i) {
    if (a[i] !== b[i]) {
      return false;
    };
  }
  return true;
}

对于您的代码:

let props:(string|boolean)[]=['abc','def',true,false,'xyz']
let propsCopied:(string|boolean)[]=['abc','def',true,false,'xyz']
let allPropsCopied:boolean = arraysEqual(props, propsCopied);
4ktjp1zp

4ktjp1zp3#

这对我很有效“JSON.stringify(props)===JSON.stringify(propsCopied)

相关问题