您可以通过不同的方式避免数组的重复
let preferredCountries: [ "gh", "dz","ao","bj","bw","bf","bi","cm","cf","td","km","cd","dj","eg","gq","er","sz","et","ga","gm","gq","gw","ke","ls","lr","ly","mg","mw","ml","mr","mu","ma","mz","na","ne","ng","rw","sn","sc","sl","so","za","ss","sd","tz","tg","tn","ug","zm","zw" ],
let NewpreferredCountries= [...new Set(chars)];
console.log(NewpreferredCountries);
另一种方法是
let preferredCountries: [ "gh", "dz","ao","bj","bw","bf","bi","cm","cf","td","km","cd","dj","eg","gq","er","sz","et","ga","gm","gq","gw","ke","ls","lr","ly","mg","mw","ml","mr","mu","ma","mz","na","ne","ng","rw","sn","sc","sl","so","za","ss","sd","tz","tg","tn","ug","zm","zw" ],
let NewpreferredCountries= preferredCountries.filter((c, index) => {
return preferredCountries.indexOf(c) === index;
});
console.log(NewpreferredCountries);
您还可以使用 forEach() 和 include() 从数组中删除重复项
let preferredCountries: [ "gh", "dz","ao","bj","bw","bf","bi","cm","cf","td","km","cd","dj","eg","gq","er","sz","et","ga","gm","gq","gw","ke","ls","lr","ly","mg","mw","ml","mr","mu","ma","mz","na","ne","ng","rw","sn","sc","sl","so","za","ss","sd","tz","tg","tn","ug","zm","zw" ],
let NewpreferredCountries= [];
preferredCountries.forEach((c) => {
if (!NewpreferredCountries.includes(c)) {
NewpreferredCountries.push(c);
}
});
console.log(NewpreferredCountries);