javascript - 根据匹配的 API 结果呈现文本 - Axios/JS
问题描述
我有这个工作,但它确实消耗了相当多的空间。
我想知道是否有办法对其进行更多重构,将 API 结果与更小的重构条件相匹配,也许?
axios.js
import axios from 'axios';
export const Models = () => {
return axios.get('data/cars.json')
.then(response => {
return response.data
})
}
文件.js
import { Models } from './axios';
let carModels = Models();
carModels.then((result) => {
var i, j, match;
match = false;
for (i = 0; i < result.length; i++) {
for (j = 0; j < result[i].countries.length; j++) {
if (result[i].countries[j].price == price &&
result[i].color == color &&
result[i].brand == brand &&
result[i].model == model &&
result[i].speed == speed)
{
match = true;
return document.querySelector('#brandTitle').textContent = result[i].brand;
}
}
}
if (match == false) {
console.log('No match found.');
}
})
解决方案
您可以使用some()
它来确保在满足条件时终止循环
carModels.then(result => {
var i, j, match;
match = false;
for (i = 0; i < result.length; i++) {
match = result[i].countries.some(country => {
if (
country.price == price &&
result[i].color == color &&
result[i].brand == brand &&
result[i].model == model &&
result[i].speed == speed
) {
document.querySelector('#brandTitle').textContent = result[i].brand;
return;
}
});
}
if (match == false) {
console.log('No match found.');
}
});
为了提高效率,您也可以some
在父循环上使用
carModels.then(result => {
var match;
match = false;
result.some(res => {
match = result[i].countries.some(country => {
if (
country.price == price &&
res.color == color &&
res.brand == brand &&
res.model == model &&
res.speed == speed
) {
document.querySelector('#brandTitle').textContent = res.brand;
return;
}
});
if (match) {
return;
}
});
if (match == false) {
console.log('No match found.');
}
});
推荐阅读
- api - 特定时间范围的 Prometheus 数据备份
- python - 无法使用 matplotlib 绘制图形显示错误?
- typescript - ESLint 配置中的“parser”和“parserOptions.parser”有什么区别?
- angular - 使用 Angular 中的主题通过服务向组件发送数据
- java - 如何将java文件转换为在Android上运行的apk
- go - 无法在 WSL 上安装 go 工具
- java - 使用 Jackson 转换日期/时间时保留时区信息
- microsoft-graph-api - 从 Microsoft Graph 客户端获取响应标头
- css - 如何使图像溢出容器宽度而不是 100% 高度上的翘曲
- java - 为什么我自己的异常不需要参数?