由于某些原因,控制台中未显示以下操作的doubleArray。在两种情况下,我在for循环之后声明的任何变量都不会显示在控制台上。考虑到在第一个算法中,只有一个for循环,x每次都递增。而在第二种算法中,它是嵌套的for循环。有人可以帮我解决两种算法中的错误吗?第一种算法:
var isDuplicate = function() {
var helloWorld = [1,2,3,4,3];
var doubleValue = [];
var x = 0;
for (i = 0; i < helloWorld.length; i++) {
x = x + 1;
if (helloWorld[i] === helloWorld[x] && i !== x) {
doubleValue.push(helloWorld[i])
console.log(helloWorld[i]);
} else {
continue;
}
}
console.log(doubleValue);
};
第二种算法:
var isDuplicate = function() {
var helloWorld = [1,2,3,4,3];
var doubleValue = [];
for (i = 0; i < helloWorld.length; i++) {
for (x = 1; x < helloWorld.length; i++) {
if (helloWorld[i] === helloWorld[x] && i !== x) {
doubleValue.push(helloWorld[x]);
}
}
}
console.log(doubleValue);
};
您的第一个算法不起作用,因为它仅查找彼此相邻的重复项。您可以通过先对数组进行排序,然后查找重复项来修复它。您还可以在循环中删除x
和替换为++i
。
var isDuplicate = function() {
var helloWorld = [1,2,3,4,3,6];
var doubleValue = [];
helloWorld = helloWorld.sort((a, b) => { return a - b });
for (i = 0; i < helloWorld.length; i++) {
if (helloWorld[i] === helloWorld[++i]) {
doubleValue.push(helloWorld[i])
console.log(helloWorld[i]);
} else {
continue;
}
}
console.log(doubleValue);
};
isDuplicate();
对于第二个算法循环,您可能要x++
代替i++
第二个循环。这样可以解决问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句