首页 > 解决方案 > 无法在 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;
  }
});

标签: javascriptarrays

解决方案


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);


推荐阅读