[英]Finding product of values in Javascript
Write a function called productOfValues which takes in an object of key/value pairs and multiplies the values together.编写一个名为 productOfValues 的函数,它接收一个键/值对对象并将这些值相乘。 You can assume that all keys are strings and all values are integers.您可以假设所有键都是字符串,所有值都是整数。
For example:例如:
let testObject = {
'a': 5,
'b': 12,
'c': 3
}
productOfValues(testObject)
So, this is what I wrote:所以,这就是我写的:
let testObject = { 'a': 5, 'b': 12, 'c': 3, 'd': 1 } let testObject_v = { 'z': 2, 'y': 2, 'x': 2, 'w': 2 } function productOfValues(someObject) { return someObject.a * someObject.b * someObject.c; } function productOfValues(testObject) { return testObject_v.z * testObject_v.y * testObject_v.x * testObject_v.w; } console.log(productOfValues(testObject)) console.log(productOfValues(testObject_v))
And I've got an error of:我有一个错误:
Your productOfValues function should return the product of the values in the given object: 180您的 productOfValues 函数应该返回给定对象中值的乘积:180
You can use Object.values
to convert your object to array of its values & then use reduce
to get the product of that values array您可以使用Object.values
将您的对象转换为其值的数组,然后使用reduce
来获取该值数组的乘积
let testObject = {'a': 5,'b': 12,'c': 3, 'd':1}; let testObject_v = { 'z':2,'y':2,'x':2,'w':2 } function productOfValues(someObject) { return Object.values(someObject).reduce((a,b)=> a*b ,1); } console.log(productOfValues(testObject)); console.log(productOfValues(testObject_v));
You're defining the same function twice and you're only multiplying the first 3 numbers in the first object.您定义了两次相同的函数,并且您只是将第一个对象中的前 3 个数字相乘。 Instead, rewrite your productOfValues()
function to be something like this:相反,将您的productOfValues()
函数重写为如下所示:
let testObject = { 'a': 5, 'b': 12, 'c': 3, 'd': 1 } let testObject_v = { 'z': 2, 'y': 2, 'x': 2, 'w': 2 } function productOfValues(someObject) { let product = 1; for (const i in someObject) { product = product * someObject[i]; } return product; } console.log(productOfValues(testObject)) console.log(productOfValues(testObject_v))
Edit: Alternative productOfValues()
function:编辑:替代productOfValues()
函数:
function productOfValues(someObject) {
var result = 1;
var len = Object.keys(someObject).length;
for (var i = 0; i < len; i++) {
result = result * someObject[Object.keys(someObject)[i]];
}
return result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.