Javascript 根据匹配的API结果呈现文本-Axios/JS

Javascript 根据匹配的API结果呈现文本-Axios/JS,javascript,axios,Javascript,Axios,我有这个工作,但它确实消耗了相当多的空间 我想知道是否有办法对它进行更多的重构,也许是将API结果与更小的重构条件相匹配 axios.js 从“axios”导入axios; 导出常量模型=()=>{ 返回axios.get('data/cars.json') 。然后(响应=>{ 返回响应.data }) } file.js 从“/axios”导入{Models}; 设carModels=Models(); carModels.then((结果)=>{ 变量i,j,匹配; 匹配=假; 对于(i=

我有这个工作,但它确实消耗了相当多的空间

我想知道是否有办法对它进行更多的重构,也许是将API结果与更小的重构条件相匹配

axios.js
从“axios”导入axios;
导出常量模型=()=>{
返回axios.get('data/cars.json')
。然后(响应=>{
返回响应.data
})
}
file.js
从“/axios”导入{Models};
设carModels=Models();
carModels.then((结果)=>{
变量i,j,匹配;
匹配=假;
对于(i=0;i
您可以使用
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 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.');
    }
});


如果您在for loopIts中使用return语句并将其导入mutationorserver函数中,这是如何工作的。它返回数据,我在Observer中使用该数据。如果满足条件,您正在更改DOM值及其id选择器,因此我假设您将只获得一个匹配项,对吗?正确,我已经声明了color/speed/model的值/内容,但不在上面的示例中。我得到了一个正确的匹配项,我检查了API响应,结果是正确的。让我知道下面的解决方法有助于您在for loopIts中使用return语句并将其导入到mutationorserver函数中。它返回数据,我在Observer中使用该数据。如果满足条件,您正在更改DOM值及其id选择器,因此我假设您将只获得一个匹配项,对吗?正确,我已经声明了color/speed/model的值/内容,但不在上面的示例中。我得到了一个正确的匹配,我检查了API响应,结果是正确的。让我知道下面的解决方法帮助您工作,非常感谢!因此
some()
一旦找到匹配项,就结束循环。是的,这是正确的,了解更多关于它的工作原理,非常感谢!因此
some()
一旦找到匹配项,就结束循环。是的,这是正确的,了解更多信息