gpt4 book ai didi

javascript - 使用for循环将重复的项目插入Javascript中的单独数组?

转载 作者:行者123 更新时间:2023-12-01 15:21:43 25 4
gpt4 key购买 nike

出于某种原因,控制台中未显示下面操纵的 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);
};

最佳答案

在第一个算法中,您只检查当前索引处的数字是否等于下一个索引处的数字,这意味着您只比较连续索引处的数字。只有在连续索引上有重复数字时,第一个算法才有效。

在第二种算法中,您正在递增 i在两个循环中,递增 x在嵌套循环中,更改 x = 1x = i + 1你的错误将得到修复。

这是固定的第二个代码片段

var isDuplicate = function() {
var helloWorld = [1,2,3,4,3, 1, 2];
var doubleValue = [];
for (let i = 0; i < helloWorld.length; i++) {
for (let x = i + 1; x < helloWorld.length; x++) {
if (helloWorld[i] === helloWorld[x] && i !== x) {
doubleValue.push(helloWorld[x]);
}
}
}
console.log(doubleValue);
};

isDuplicate();


这是使用对象在数组中查找重复项的另一种方法。遍历数组,如果当前数字作为对象中的键存在,则将当前数字压入 doubleValue数组,否则将当前数字作为键值对添加到对象中。

const isDuplicate = function() {
const helloWorld = [1,2,3,4,3, 1, 2];
const doubleValue = [];
const obj = {};

helloWorld.forEach(n => obj[n] ? doubleValue.push(n): obj[n] = n);

console.log(doubleValue);
};

isDuplicate();

关于javascript - 使用for循环将重复的项目插入Javascript中的单独数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62188963/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com