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

Ember模型与计算属性问题:如何获取最高价对应书籍标题

获取最高价书籍及其标题的解决方案

嘿,这个需求很好实现,咱们只需要再加一个计算属性就能搞定啦!

你现在已经通过mapBy和max拿到了最高价格,接下来只需要从书籍数组里找到价格等于这个最高价的那本书,就能拿到对应的标题了。

步骤1:添加计算属性找到对应书籍

在你的组件/模型里新增一个计算属性,比如maxPriceBook,利用数组的find方法匹配价格:

// 你的现有计算属性
allPrices: mapBy('books', 'price'),
maxPrice: max('allPrices'),

// 新增的计算属性,找到对应最高价的书籍
maxPriceBook: computed('books', 'maxPrice', function() {
  // 先判断书籍数组是否为空,避免报错
  if (!this.books.length) return null;
  // 找到第一个价格等于最高价的书籍
  return this.books.find(book => book.price === this.maxPrice);
})

步骤2:在模板中显示标题

现在你就可以在模板里直接调用这个计算属性的title属性了:

{{!-- 显示最高价和对应书名 --}}
<p>最高价格:{{maxPrice}}</p>
<p>对应书籍:{{maxPriceBook?.title}}</p>

额外情况:处理多本最高价书籍

如果有多本书价格都是最高值,你可以把find换成filter,拿到所有符合条件的书籍,然后在模板里遍历显示:

maxPriceBooks: computed('books', 'maxPrice', function() {
  if (!this.books.length) return [];
  return this.books.filter(book => book.price === this.maxPrice);
})

模板里遍历显示:

<p>最高价格:{{maxPrice}}</p>
<p>对应书籍:</p>
<ul>
  {{#each maxPriceBooks as |book|}}
    <li>{{book.title}}</li>
  {{/each}}
</ul>

这样就能完美实现同时显示最高价和对应书籍标题的需求啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:23:12