创建一个临时数组,它是 arr1 的副本,仅包含唯一值:
// Copy unique values in arr1 into temp_arr
var temp_obj = {}, temp_arr = [], i;
for(i = arr1.length; i--;)
temp_obj[arr1[i]] = 1;
for(i in temp_obj)
temp_arr.push(i);
然后您可以在每次将元素添加到arr2 时从temp_arr 中删除它。由于我们在复制字符串时使用了对象键,所以我们可以在推入arr2时使用+将它们转换回数字:
arr2.push(+temp_arr.splice(rand, 1)[0]);
您还应该将选择随机数的方式更改为:
var rand = Math.floor(Math.random()*temp_arr.length);
完整代码:
var limit = 5,
arr1 = [12, 14, 67, 45, 8, 45, 56, 8, 33, 89],
arr2 = [],
rand,
temp_obj = {},
temp_arr = []
i;
// Copy unique values from arr1 into temp_arr
for(i = arr1.length; i--;)
temp_obj[arr1[i]] = 1;
for(i in temp_obj)
temp_arr.push(i);;
// Move elements one at a time from temp_arr to arr2 until limit is reached
for (var i = limit; i--;){
rand = Math.floor(Math.random()*temp_arr.length);
arr2.push(+temp_arr.splice(rand, 1)[0]);
}
console.log(arr2);