试图从另一个数组创建一个重复值数组,为什么我的代码不起作用?

时间:2018-04-17 00:21:01

标签: javascript arrays performance

我正在处理这段代码,其目标是创建一个包含从另一个数组复制的所有值的数组。我想要的结果数组应该只输入第一个数组的重复值。 问题是我不能使用任何数组函数或方法。这就是我到目前为止所做的:

var numbers = [8,24,20,5,13,3,1,12,11,24,8,24,20,4,5,23,24,23,21,2,19,3,21,2,14,17,21,5,7,10,20,11,0,5,18,2,13,11,14,3,20,1,23,6,21,10,14,0,15,20];

var results = [];
var tempArr = [];

for (var i = 0; i <= numbers.length; i++) {
  if (tempArr[numbers[i]] === undefined) {
    tempArr[numbers[i]] = 1;
  } else if (results[numbers[i]] === undefined)  {
    results.push(numbers[i]);
  }
}

console.log(tempArr);
console.log(results);

我越来越接近我想要的输出......但由于某种原因,结果数组继续包含数字数组中重复的值的多个条目。我在哪里错了?

1 个答案:

答案 0 :(得分:1)

你基本上滥用数组作为对象。尝试使用对象来记录您的值(并为该对象提供一个代表其所包含内容的名称),它将大大简化您的代码:

&#13;
&#13;
var numbers = [8,24,20,5,13,3,1,12,11,24,8,24,20,4,5,23,24,23,21,2,19,3,21,2,14,17,21,5,7,10,20,11,0,5,18,2,13,11,14,3,20,1,23,6,21,10,14,0,15,20];

var results = [];
var seenValues = {};

for (var i = 0; i < numbers.length; i++) {
  const number = numbers[i];
  seenValues[number] = 1 + (seenValues[number] || 0);
  // check to see if it's been seen exactly once before,
  // so that the duplicated value is only added once:
  if (seenValues[number] === 2) results[results.length] = number;
}

//console.log(seenValues);
console.log(results);
&#13;
&#13;
&#13;