首页 > 解决方案 > 根据匹配的 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.');
  }
})

标签: javascriptaxios

解决方案


您可以使用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.');
    }
});

推荐阅读