首页 > 解决方案 > 如何将循环更改为地图?

问题描述

我还没有找到将 for 更改为 a 的方法map,所以我的计划不会使用 for 但想在此函数的每个函数中使用映射

variantDefault = (colorId, sizeId) => {
  let selected = [];
  let i = 0;
  if (this.props.index === 0) {
    for (i = 0; i < this.props.values.length; i++) {
      if (this.props.values[i].id === colorId) {
        selected = this.props.values[i];
      }
    }
  }
  if (this.props.index === 1) {
    for (i = 0; i < this.props.values.length; i++) {
      if (this.props.values[i].id === sizeId) {
        selected = this.props.values[i];
      }
    }
  }
  console.log(selected);
  return selected;
};

标签: javascriptreactjsecmascript-6

解决方案


你可以试试这种方式

variantDefault = (colorId, sizeId) => {
let selected = [];
if (this.props.index === 0) {
   this.props.values.map((data) => {
    if(data.id === colorId){
    selected.push(data)
    }
  })
}
if (this.props.index === 1) {
this.props.values.map((data) => {
  if (data.id === sizeId) {
    selected.push(data)
  }
})
}
console.log(selected);
return selected;
 };

推荐阅读