javascript - 如何将循环更改为地图?
问题描述
我还没有找到将 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;
};
解决方案
你可以试试这种方式
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;
};
推荐阅读
- ios - 如何在 SwiftUI 中创建此视图?
- pandas - 如何将矩阵作为字符串转换为ndarray?
- python - 无法弄清楚为什么 soup.find_all() 返回一个空列表
- ruby-on-rails - 如何使用正则表达式从 Ruby 中的 str.scan 和 str.match 返回相同的结果
- python - 烧瓶注销特定用户的所有会话
- java - java DatagramSocket中如何发送对象不实现Serializable接口
- c++ - 旋转二维数组的最快方法
- r - 更改 r 中数字命名列的顺序
- java - 如何打印 LinkedHashMap
- java - 稳定的项目还应该使用 spring-boot-starter-* 吗?