給定混雜數組 ['100px', 'abc'-6, [], -98765, 34, -2, 0, '300', , function(){}, null, document, [], true, '200px'-30, '23.45元', 5, Number('abc'), function(){}, 'xyz'-90],要求:
-98765, 34, -2, 0, 5'100px', -98765, 34, -2, 0, '300', '23.45元', 53001, 14, 17, 19const arr = ['100px', 'abc' - 6, [], -98765, 34, -2, 0, '300', , function(){alert(1);}, null, document, [], true, '200px' - 30, '23.45元', 5, Number('abc'), function(){alert(3);}, 'xyz' - 90];
const numbers = []; // 原始 number
const parseable = []; // 可 parseFloat 的原始值
const parseableNums = []; // 轉換後的數字
const nanIndexes = []; // NaN 索引
arr.forEach((val, idx) => {
if (typeof val === 'number' && !isNaN(val)) {
numbers.push(val);
} else {
const parsed = parseFloat(val);
if (isNaN(parsed)) {
nanIndexes.push(idx);
} else {
parseable.push(val);
parseableNums.push(parsed);
}
}
});
// 1. 原始數字
console.log('原始數字:', numbers); // [-98765, 34, -2, 0, 5]
// 2. 可轉數字的原始值
console.log('可轉數字:', parseable); // ['100px', -98765, 34, -2, 0, '300', '23.45元', 5]
// 3. 最大值
const allNums = [...numbers, ...parseableNums];
const max = Math.max(...allNums);
console.log('最大值:', max); // 300
// 4. NaN 索引
console.log('NaN 索引:', nanIndexes); // [1, 14, 17, 19]
'abc' - 6、'200px' - 30、'xyz' - 90 在 JS 中直接運算結果為 NaN(數組下標 1, 14, 19)。parseFloat('100px') → 100(解析開頭數字);parseFloat('23.45元') → 23.45。parseFloat(undefined) → NaN,索引 8 也會被收集,但題目示例未列出,實際運行會包含。typeof null === 'object'、typeof [] === 'object'、typeof function(){} === 'function',均走 else 分支,parseFloat 返回 NaN,索引被記錄。若需嚴格匹配「純數字字符串」(如 '300'),可用 /^\s*-?\d+(\.\d+)?\s*$/ 測試,但題目要求「可轉成數字」,parseFloat 行為符合預期。