JavaScript数组元素类型匹配及存在性判断问题求助
Let's work through your two requirements and fix the issues with your has function step by step.
First Requirement: Check if All Array Elements Are the Same Type
To reliably check if every element in an array shares the exact same type, we need to avoid typeof quirks (like it returning "object" for null and arrays). Using Object.prototype.toString.call() gives us a precise type string for any value.
Here's a function that handles this correctly:
function areAllSameType(arr) { if (arr.length === 0) return true; // Adjust to false if empty arrays should return false for your use case // Helper to get precise type of a value const getPreciseType = (val) => { return Object.prototype.toString.call(val).slice(8, -1); }; const firstElementType = getPreciseType(arr[0]); // Verify every element matches the first element's type return arr.every(element => getPreciseType(element) === firstElementType); } // Test cases console.log(areAllSameType([1, 2, 3])); // true (all numbers) console.log(areAllSameType([1, "2", 3])); // false (mix of number and string) console.log(areAllSameType([{a:1}, {b:2}])); // true (all objects) console.log(areAllSameType([[], [1,2]])); // true (all arrays)
Second Requirement: Fix the has Function to Check Existence with Type Match
Your original has function has critical logic flaws that prevent it from working correctly—even when using ===:
- The
switchstatement is misused: You're switching ondecision(which starts astrue), so it will only ever match cases that evaluate totrue, and your case conditions are structured incorrectly for how switch works. - You reset
decisiontotrueon every loop iteration, overwriting any previous check results. - You return the last iteration's
decisionvalue instead of checking if any element matched at all.
Here's the corrected function that uses strict equality (===) to check for both value and type match, and returns as soon as a match is found:
function has(list, element) { for (let i = 0; i < list.length; i++) { if (list[i] === element) { console.log(`Yes, ${JSON.stringify(element)} exists in the array with matching type.`); return true; // Return immediately when a match is found } } console.log(`No, ${JSON.stringify(element)} does not exist (or type doesn't match).`); return false; // Return false if no matches are found after full loop } // Test with your sample array var data = [1, 2, {a: 1}, [43], '3']; console.log(has(data, 1)); // true (matches the first element) console.log(has(data, 43)); // false (array has [43], not the number 43 itself) console.log(has(data, 3)); // false (no element 3 exists) console.log(has(data, '3')); // true (matches the last string element)
This function behaves exactly as you expect: it returns true only when an element exists in the array with both the same value and type (thanks to ===), and false otherwise.
内容的提问来源于stack exchange,提问作者IkePr

