从打字稿中删除数组中的重复项

时间:2020-08-09 04:55:05

标签: javascript typescript ecmascript-6

我是TypeScript的新手,在使用JavaScript技能时遇到了一些问题。例如,有人可以帮我在打字稿中写下面完全相同的javascript代码吗?

如果根本不可能,任何打字稿函数都会呈现预期的输出(没有重复值的数组)。

这只是从数组中删除重复项的一种简单方法,但是好像打字稿不能让我定义一个空对象...我不确定...

下面的代码输出为:['John','Paul','George','Ringo']

谢谢!

const names = ['John', 'Paul', 'George', 'Ringo', 'John'];

function removeDups(names) {
  let unique = {};
  names.forEach(function(i) {
    if(!unique[i]) {
      unique[i] = true;
    }
  });
  return Object.keys(unique);
}

removeDups(names)

2 个答案:

答案 0 :(得分:1)

在这种情况下,您只需要添加类型

const names = ['John', 'Paul', 'George', 'Ringo', 'John'];

function removeDups(names: string[]) {
  let unique: any = {};
  names.forEach(function(i: string) {
    if(!unique[i]) {
      unique[i] = true;
    }
  });
  return Object.keys(unique);
}

removeDups(names)

typescript playground

答案 1 :(得分:0)

names = ['John', 'Paul', 'George', 'Ringo', 'John']; 

removeDups(names) {
 let unique = {};
  this.names.forEach((i) => {
    if(!unique[i]) {
      unique[i] = true;
    }
  });
  return Object.keys(unique);
}

然后从需要的地方致电removeDups

这里是another way

names = ['John', 'Paul', 'George', 'Ringo', 'John']; 

removeDups(names) {

  return this.names.filter((elem, index, self)=> {
    return index === self.indexOf(elem);
})
}