使用OpenWhisk与JavaScript计算JSON对象元素总和遇0结果问题求助
Hey there! Let's troubleshoot why your OpenWhisk JavaScript action is returning 0 instead of the correct total (2+56+99+12 = 169) for your input {0: 2, 1: 56, 2: 99, 3:12}.
Common Causes & Fixes
Most likely, the issue comes from either targeting the wrong part of the input object or not properly handling object properties during traversal. Here are the most straightforward solutions:
1. You're Traversing the Wrong Object
OpenWhisk wraps input data differently depending on how you trigger the action:
- If you pass the JSON directly as action parameters (via CLI or UI), the key-value pairs live in the top-level
paramsobject. - If you trigger the action via an HTTP request (e.g., API Gateway), the parsed JSON input is usually nested under
params.body.
Fix for direct parameter input:
function main(params) { let sum = 0; // Loop through all own properties of the params object for (const key in params) { if (params.hasOwnProperty(key)) { const value = params[key]; // Ensure we only add numeric values if (typeof value === 'number') { sum += value; } } } return { totalSum: sum }; }
Fix for HTTP body input:
function main(params) { let sum = 0; // Fallback to empty object if body doesn't exist const inputData = params.body || {}; for (const key in inputData) { if (inputData.hasOwnProperty(key)) { const value = inputData[key]; if (typeof value === 'number') { sum += value; } } } return { totalSum: sum }; }
2. Why Your Original Code Returned 0
The most probable reasons are:
- You were iterating over an empty or incorrect object (e.g.,
paramsinstead ofparams.body), so the loop never added anything to the initialsum = 0. - You didn't check for
hasOwnProperty, which could lead to iterating over inherited properties (which might have non-numeric or zero values).
Debugging Tip
To confirm exactly what input your action is receiving, add a console log at the start of your function:
function main(params) { console.log('Received params:', JSON.stringify(params)); // Rest of your code... }
Then check the action logs via the OpenWhisk CLI with wsk activation logs <activation-id> to see the structure of the incoming data.
内容的提问来源于stack exchange,提问作者zak

