javascript - 无法在 JS forEach 中使用变量
问题描述
我正在尝试检查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 - .click() 不适用于触摸屏设备和 chrome,但它适用于 pc 上的 firefox
- powershell - 将 AD 用户描述添加到属于特定 OU 的用户
- python - 如何将 Python 训练的 ML 模型集成到 Node.Js 中
- typescript - 使用 Angular 获取 API 调用打字稿
- windows - 有人可以解释 Git Bash CLI 没有正确显示字符吗?
- java - java.lang.IllegalArgumentException:不是带有 @Entity 和 @Repository 的托管类型 使用 Spring Boot 2 设置
- python - 两个字符串数组的乘积
- assembly - 操作码到字节的主要图表
- android - java.lang.IllegalStateException:没有maybeRun就不能取消调用
- python - 解码法语口音不适用于 utf-8