如何使用javascript获取对象的属性值

How to get property values of object using javascript

本文关键字:属性 取对象 获取 何使用 javascript      更新时间:2023-09-26

我有一个具有多个属性和值的对象。如何一次取完?

在下面的代码中,产品有多个值。我想获取所有的价格,并使用java脚本求出它们的总和

代码如下。

var products = [
    {name:"anti-glair", price:100, quantity:200, status:"available"},
    {name:"Lens", price:300, quantity:35, status:"Un-available"},
    {name:"Optics", price:150, quantity:500, status:"available"}
    ];

我试着像这个

console.log(products.price);

但它显示为未定义。

我也想要所有产品的总和。

products指的是一个数组。您可以使用索引0访问该数组中的第一个对象,使用索引1访问第二个对象,等等。或者,您可以使用for循环、products.forEach或本问题答案中列出的许多其他方式循环访问该数组。

一旦有了对象,就可以使用所显示的语法访问其属性。

例如:

var products = [
    {name:"anti-glair", price:100, quantity:200, status:"available"},
    {name:"Lens", price:300, quantity:35, status:"Un-available"},
    {name:"Optics", price:150, quantity:500, status:"available"}
    ];
console.log(products[0].price);

使用高阶函数。要获得一系列价格,

let prices = products.map(x => x.price)

综上所述,

let totalCost = prices.reduce((x, y) => x + y)

对于迭代和获取总和或价格,请使用Array#reduce方法

var sum = products.reduce(function(a, b) {
  // calculate the price and add with total
  // multiply with `quantity` property if you want
  return a + b.price;
  // set initial value as 0
}, 0);

var products = [{
  name: "anti-glair",
  price: 100,
  quantity: 200,
  status: "available"
}, {
  name: "Lens",
  price: 300,
  quantity: 35,
  status: "Un-available"
}, {
  name: "Optics",
  price: 150,
  quantity: 500,
  status: "available"
}];
var sum = products.reduce(function(a, b) {
  return a + b.price;
}, 0);
console.log(sum)

试试这就是你想要的。

var products = [
    {name:"anti-glair", price:100, quantity:200, status:"available"},
    {name:"Lens", price:300, quantity:35, status:"Un-available"},
    {name:"Optics", price:150, quantity:500, status:"available"}
    ];
var TotalPrice = 0;
var obj = {};
for(var i = 0; i< products.length; i++){
  TotalPrice = TotalPrice + products[i].price;
  obj[i] = { price : products[i].price};
}
obj.total_price = TotalPrice;
console.log(obj);

在迭代其余数据之前,首先获取对象的长度:

var products = [
    {name:"anti-glair", price:100, quantity:200, status:"available"},
    {name:"Lens", price:300, quantity:35, status:"Un-available"},
    {name:"Optics", price:150, quantity:500, status:"available"}
    ];
var sumPrices = 0;
for(i = 0; i < products.length; i++) {
  console.log("Name: " + products[i].name + ", Price: " + products[i].price + ", Quantity: " + products[i].quantity[i] + ", Status: " + products[i].status);  
  sumPrices = sumPrices + products[i].price; 
}
console.log("Total sum of prices: " + sumPrices);