Middle
/* È necessario scrivere una funzione per calcolare la somma di tutti i valori numerici in un array. Valori numerici validi sono anche stringhe, che iniziano con cifre. In questo caso, bisogna usare questa sequenza iniziale di cifre come valore numerico. L'array può contenere qualsiasi tipo di dato e non essere piatto. **Non si devono usare metodi integrati come .flat, .flatMap** */ function sum(arr) { // ... } console.log(sum([1, 'x', '2x', ['3', ['x2', '5']]]));
sobes.tech AI
Risposta dell'AI
javascript function sum(arr) { let total = 0;
function helper(a) { for (const item of a) { if (typeof item === 'number') { total += item; } else if (typeof item === 'string') { const match = item.match(/^\d+/); if (match) { total += Number(match[0]); } } else if (Array.isArray(item)) { helper(item); } // Другие типы игнорируем } }
helper(arr); return total; }
console.log(sum([1, 'x', '2x', ['3', ['x2', '5']]])); // 11
Функция рекурсивно обходит массив, проверяет каждый элемент:
- Если число — добавляет к сумме.
- Если строка, пытается извлечь начальную последовательность цифр и добавить её.
- Если массив — рекурсивно вызывает себя.
- Остальные типы игнорируются.
Так мы считаем сумму всех числовых значений и строк, начинающихся с цифр, без использования `.flat` или `.flatMap`.