如何通过加入数组中包含的字符串来生成随机URL(还应消除重复项)?
字符串数组
let array=['flip','amazon','ebay','amazon']
预期产量
['http://www.flip.com','http://www.amazon.com','http://www.ebay.com']
答案 0 :(得分:0)
您可以尝试以下操作:
let array = ['flip', 'amazon', 'ebay', 'amazon']
/** Generating random number between 0 to length of array **/
let index = Math.floor(Math.random() * array.length);
console.log(`http://www.${array[index]}.com`);
答案 1 :(得分:0)
尝试
const array=['flip','amazon','ebay','amazon']
/*
[
'http://www.flip.com',
'http://www.amazon.com',
'http://www.ebay.com'
]
*/
const keywords = []
for (const keyword of array) {
if (!keywords.includes(keyword)) {
keywords.push(keyword)
}
}
const result = keywords.map(item => `http://www.${item}.com`)
console.log(result)
答案 2 :(得分:0)
您可以使用Set删除重复项,并且一次只能选择一个随机值,而不能随机选择整个数组。
let array=['flip','amazon','ebay','amazon']
let result=new Set(array.map(ele=>`http://www.${ele}.com`))
// your expected output
console.log(Array.from(result)) // select random from here if this is what you looking for
//for getting random values
var rand = Array.from(result)[Math.floor(Math.random() * Array.from(result).length)];
console.log(rand)
从here引用的随机值生成
答案 3 :(得分:0)
首先创建网址-然后使用Set
删除重复项:
let array = ['flip', 'amazon', 'ebay', 'amazon']
const res = [...new Set(array.map(e => `http://www.${e}.com`))];
console.log(res);
您还可以通过两种方式使用reduce
:
let array = ['flip', 'amazon', 'ebay', 'amazon']
const res = [...array.reduce((a, c) => (a.add(`http://www.${c}.com`), a), new Set())];
console.log(res);
或者:
let array = ['flip', 'amazon', 'ebay', 'amazon']
const res = Object.values(array.reduce((a, c) => (a[c] = a[c] || `http://www.${c}.com`, a), {}));
console.log(res);