首页 > 解决方案 > 显示一本书的平均价格

问题描述

我需要一些代码来实现计算书籍的平均价格,罗马的类型。类型字段可以写成任何大小写(罗马、罗马)。

let books = [
    { name: 'Some-1', author: 'Puskin', type: 'roman', price: 204.5 },
    { name: 'Some-2', author: 'Tolstoy', type: 'ROMAN', price: 321.0 },
    { name: 'Some-3', author: 'Pero', type: 'tale', price: 211.0 },
    { name: 'Some-4', author: 'Koelyo', type: 'roman', price: 204.5 },
    { name: 'Some-5', author: 'Christie', type: 'Roman', price: 245.5 },
    { name: 'Some-6', author: 'Hohol', type: 'tale', price: 366.0 }
];

所以我用这个方法派生了所有类型:

const getType = books.map(({type}) => type.toLowerCase())

而且我的问题是我不知道如何获得价格

标签: javascript

解决方案


你可以用几种方法做到这一点

您可以循环遍历数组并总结那里的所有价格,然后根据其长度划分,您还将检查当前对象类型是否等于roman,使用.toLowerCase()

如果要返回自然数,可以使用.toFixed()方法

循环

let books = [
    { name: 'Some-1', author: 'Puskin', type: 'roman', price: 204.5 },
    { name: 'Some-2', author: 'Tolstoy', type: 'ROMAN', price: 321.0 },
    { name: 'Some-3', author: 'Pero', type: 'tale', price: 211.0 },
    { name: 'Some-4', author: 'Koelyo', type: 'roman', price: 204.5 },
    { name: 'Some-5', author: 'Christie', type: 'Roman', price: 245.5 },
    { name: 'Some-6', author: 'Hoho', type: 'tale', price: 366.0 }
 ]
 
let TotalPrice = 0;
let romanPriceLength = 0;

for (let i = 0; i < books.length; i++) {
  if ((books[i].type).toLowerCase() === "roman") {
    TotalPrice += books[i].price
    romanPriceLength++
  }
}

console.log(TotalPrice / romanPriceLength)
console.log((TotalPrice / romanPriceLength).toFixed(0))

forEach()

let books = [
    { name: 'Some-1', author: 'Puskin', type: 'roman', price: 204.5 },
    { name: 'Some-2', author: 'Tolstoy', type: 'ROMAN', price: 321.0 },
    { name: 'Some-3', author: 'Pero', type: 'tale', price: 211.0 },
    { name: 'Some-4', author: 'Koelyo', type: 'roman', price: 204.5 },
    { name: 'Some-5', author: 'Christie', type: 'Roman', price: 245.5 },
    { name: 'Some-6', author: 'Hoho', type: 'tale', price: 366.0 }
 ]


let TotalPrice = 0;
let romanPriceLength = 0;

 books.forEach(book => {
  if((book.type).toLowerCase() === "roman"){
    TotalPrice += book.price
    romanPriceLength ++
  }
 })
 
 console.log(TotalPrice / romanPriceLength)
 console.log((TotalPrice / romanPriceLength ).toFixed(0))

对于...的

let books = [
    { name: 'Some-1', author: 'Puskin', type: 'roman', price: 204.5 },
    { name: 'Some-2', author: 'Tolstoy', type: 'ROMAN', price: 321.0 },
    { name: 'Some-3', author: 'Pero', type: 'tale', price: 211.0 },
    { name: 'Some-4', author: 'Koelyo', type: 'roman', price: 204.5 },
    { name: 'Some-5', author: 'Christie', type: 'Roman', price: 245.5 },
    { name: 'Some-6', author: 'Hoho', type: 'tale', price: 366.0 }
 ]

let romanPriceLength = 0;
let TotalPrice = 0;

for(let book of books){
  if(book.type.toLowerCase() === "roman"){
    TotalPrice += book.price
    romanPriceLength++
  }
}

console.log(TotalPrice / romanPriceLength)
console.log((TotalPrice / romanPriceLength).toFixed(0))


推荐阅读