You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ember计算属性中如何将null值的specialty_id替换为0?

修复Ember计算属性中tspecID的null值处理问题

我一眼就发现问题出在哪了——你在idCheck函数里犯了一个拼写错误!你写的是speciality_id(少了字母c),但实际数据里的属性是specialty_id,这直接导致你的条件判断完全没按预期工作:

  • 当specialty_id是数值时,x.data.speciality_id是undefined,undefined !== null为true,所以返回x.data.specialty_id(正确的数值),看起来没问题;
  • 当specialty_id是null时,x.data.speciality_id还是undefined,undefined !== null依然为true,所以还是返回x.data.specialty_id也就是null,这就是else分支永远不执行的原因。

修复后的代码

其实完全不用单独写idCheck函数,用三元表达式就能简洁解决,同时修正拼写错误:

SpecSortData: computed('customerfr', function() {
  let newArray = [];
  this.get('customerfr').forEach((x) => {
    const tspecID = x.data.specialty_id !== null ? x.data.specialty_id : 0;
    let newData = {
      specialtyID: x.data.specialty_id,
      specialty: x.data.specialty_name,
      customerID: x.data.customer_id,
      tspecID: tspecID
    };
    newArray.push(newData);
  });
  return newArray;
}),

额外优化建议

  1. 用箭头函数代替普通函数,避免不必要的作用域问题;
  2. 如果用的是较新版本的Ember,可以用map方法简化数组生成,同时优化计算属性的依赖,让单个元素属性变化时也能触发重计算:
SpecSortData: computed('customerfr.@each.specialty_id', function() {
  return this.get('customerfr').map(x => ({
    specialtyID: x.data.specialty_id,
    specialty: x.data.specialty_name,
    customerID: x.data.customer_id,
    tspecID: x.data.specialty_id !== null ? x.data.specialty_id : 0
  }));
}),

内容的提问来源于stack exchange,提问作者Sorvah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:19:39