基于指定键对比对象数组值并统计正确率的JS实现问题
Fix: Compare Object Arrays by Key with Whitespace Handling
Got it, let's tackle this problem! The main issue with your original code is that JSON.stringify does a strict character-by-character match—so even a tiny extra space in your test data values will make the comparison fail, even if the core answer is correct. Let's rewrite this to compare each key's value directly, after cleaning up any whitespace in the test data.
Revised Code Solution
Here's the updated code that fixes the whitespace issue and compares values properly per key:
var actualObject = [ { "q1": "componentWillMount" }, { "q2": "willComponentUpdate" }, { "q3": "setState" }, { "q4": "componentUpdated" } ]; var testData = [ {q1: "componentWillMount"}, {q2: "willComponentUpdate"}, {q3: " PropTypes"}, // Notice the leading space here {q4: "componentDidMount"} ]; var marks = 0; var wrong = 0; for (var k = 0; k < actualObject.length; k++) { // Grab the current items from both arrays const actualItem = actualObject[k]; const testItem = testData[k]; // Get the key for this question (since each item is a single-key object) const questionKey = Object.keys(actualItem)[0]; // Clean up the test value: trim all leading/trailing whitespace const cleanedTestValue = testItem[questionKey]?.trim() || ''; const actualValue = actualItem[questionKey] || ''; // Now compare the cleaned value against the actual one if (cleanedTestValue === actualValue) { marks++; } else { wrong++; } } console.log(marks, wrong); // This will log: 2 2
Breakdown of What Changed
- Whitespace Trimming: We use
trim()on the test data's value to strip any leading or trailing spaces—this fixes the problem wherePropTypeswith a leading space was being marked wrong. If you need to clean internal extra spaces too, you could extend this withreplace(/\s+/g, ' ')to collapse multiple spaces into one. - Per-Key Comparison: Instead of turning the whole object into a string, we target the specific key (like
q1,q2) and compare the values directly. This is way more reliable for your use case. - Safe Value Access: The
?.optional chaining operator prevents errors if a key is missing intestData, and we default to an empty string to avoid issues withundefinedvalues.
What This Handles
- Test answers with accidental leading/trailing spaces
- Missing keys in test data (they'll be counted as wrong)
- Empty actual values (handled gracefully without errors)
内容的提问来源于stack exchange,提问作者John_ny
相关产品推荐
相关产品推荐

