gpt4 book ai didi

javascript - 无法在 JS forEach 中使用变量

转载 作者:行者123 更新时间:2023-12-02 22:47:28 26 4
gpt4 key购买 nike

我正在尝试检查 otherFeatures 数组中是否已存在某个属性。我正在使用 match 变量检查这一点。当我在 match 中控制台记录结果时,它可以正常工作,但是当我尝试在 if 语句中使用它时,它总是返回 undefined

const otherFeatures = [
{heading: "Taps", value: "Silver"},
{heading: "Taps", value: "Bronze"},
{heading: "Sink", value: "Ceramic"},
];

let features = [];

const featuresCheck = otherFeatures.forEach((item, index) => {
const match = features.forEach((feat) => {
return feat.heading === item.heading;
});
console.log("match", match);
if (match) {
console.log('match true');
} else {
features[index] = item;
}
});

最佳答案

forEach() 不返回回调函数的结果。如果你想要这样,你需要使用map()。由于 forEach() 不会返回有用的值,因此将其分配给变量是没有意义的。

const otherFeatures = [
{heading: "Taps", value: "Silver"},
{heading: "Taps", value: "Bronze"},
{heading: "Sink", value: "Ceramic"},
];

let features = [];

otherFeatures.forEach((item, index) => {
const match = features.map((feat) => {
return feat.heading === item.heading;
});
console.log("match", match);
if (match) {
console.log('match true');
} else {
features[index] = item;
}
});
console.log("features", features);

但是,在 JavaScript 中,所有数组都被认为是真实的,即使它们是空的,因此 if (match) 总是会成功。如果您想知道是否有任何元素匹配,您应该使用 some()

const otherFeatures = [
{heading: "Taps", value: "Silver"},
{heading: "Taps", value: "Bronze"},
{heading: "Sink", value: "Ceramic"},
];

let features = [];

otherFeatures.forEach((item, index) => {
const match = features.some((feat) => {
return feat.heading === item.heading;
});
console.log("match", match);
if (match) {
console.log('match true');
} else {
features[index] = item;
}
});
console.log("features", features);

关于javascript - 无法在 JS forEach 中使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58333075/

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