JavaScript 代码优化:获取新闻ID对应的状态

目标: 获取 newsIds 数组中与 thisNewsId 相匹配的新闻ID对应的状态 (status)。

原始代码:

function handleQueryNewsId() {
  loading.value = true;
  thisNewsId = formData.newsId;
  console.log('-------thisNewsId-=-', thisNewsId);

  getNewsPage({ newsId: thisNewsId, page: 1, pageSize: 10 })
    .then((data: any) => {
      console.log('查询newsid是否存在的查询getNewsPage---data---', data.rows);
      const newsIds = data.rows.map(obj => obj.newsId,obj.status);
      console.log('newsids==', newsIds);

     if (newsIds.includes(thisNewsId)) {
       // console.log('---------在,就执行【表单确定】的操作-------------------');
        console.log('---------在,就判断是否是上架??------【关联ID未上架,请重新输入】------------');
        } else {
        console.log('--------------不在就提示【ID不存在,请重新输入】---------------');
      };
      console.log('--------------判断完毕---------------');

      newsList.value = data.rows;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

优化后的代码:

function handleQueryNewsId() {
  loading.value = true;
  thisNewsId = formData.newsId;
  console.log('-------thisNewsId-=-', thisNewsId);

  getNewsPage({ newsId: thisNewsId, page: 1, pageSize: 10 })
    .then((data: any) => {
      console.log('查询newsid是否存在的查询getNewsPage---data---', data.rows);
      const newsIds = data.rows.map(obj => obj.newsId,obj.status);
      console.log('newsids==', newsIds);

     if (newsIds.includes(thisNewsId)) {
       const status = data.rows.find(obj => obj.newsId === thisNewsId).status;
       console.log('---------在,就判断是否是上架??------【关联ID未上架,请重新输入】------------');
       console.log('status==', status);
     } else {
       console.log('--------------不在就提示【ID不存在,请重新输入】---------------');
     };
      console.log('--------------判断完毕---------------');

      newsList.value = data.rows;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

解释:

  1. 使用 find() 方法在 data.rows 数组中查找与 thisNewsId 相匹配的对象。
  2. 获取匹配对象的 status 属性值,并将其存储在 status 变量中。
  3. 打印 status 的值,以查看匹配的新闻ID对应的状态。

通过以上修改,就可以从匹配到的对象中获取到对应的 status,并打印出来。

JavaScript 代码优化:获取新闻ID对应的状态

原文地址: https://www.cveoy.top/t/topic/htQK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录