function SummPositive( numbers ) {
var negatives = [];
var sum = 0;
for(var i = 0; i < numbers.length; i ) {
if(numbers[i] < 0) {
negatives.push(numbers[i]);
}else{
sum = numbers[i];
}
}
console.log(negatives);
return sum;
}
var sum_result = SummPositive( [ 1, 2, 3, 4, 5, -2, 23, -1, -13, 10,-52 ] );
console.log(sum_result);
i have some trouble, i dont know how to check if array have index string, return false, thx all for help me to fix it
CodePudding user response:
function SummPositive( numbers ) {
let negatives = []; // hold all negative number
let falsy = false; // boolean to hold true if string exists in the list
let sum = 0; // to increment all the numbers in the list
for(let num of numbers) { // loop through the list
if(typeof num == 'string') {
falsy = true // set boolean to true if string item exists in the list
break // break out of the loop
}
if (num < 0) {
negatives.push(num); // push all negative numbers to a negatives list
} else {
sum = num // update sum
}
}
return falsy ? false : sum; // return false if falsy is true else return sum
}
var sum_result = SummPositive([ '44', 1, 2, 3, 4, 5, -2, 23, -1, -13, 10,-52, '3' ]);
CodePudding user response:
The direct answer to your question of "How to check if an array element is a string" is to use the typeof
operator, specifically comparing the evaluated result to string
:
// const element = array[index];
const isAString = typeof element === 'string';
Here's an example showing how to use various array methods to help with the details of your problem.
function sum (numbers) {
let sum = 0;
for (const n of numbers) sum = n;
return sum;
}
function sortAndStringify (numbers) {
// Create a copy so the original object is not mutated by sorting
const copy = [...numbers];
return copy.sort((a, b) => a - b).join(', ');
}
function example (array) {
const stringWasFound = array.some(element => typeof element === 'string');
console.log('string was found:', stringWasFound);
// Even better (more strict): ensure that all elements are numbers
const allElementsAreNumbers = array.every(element => typeof element === 'number');
console.log('all elements are numbers:', allElementsAreNumbers);
// Return false if a non-number was found
if (!allElementsAreNumbers) return false;
// If we get this far, then we know that we are only dealing with numbers
const negatives = array.filter(n => n < 0);
console.log('negatives:', sortAndStringify(negatives));
const positives = array.filter(n => n >= 0);
console.log('positives:', sortAndStringify(positives));
console.log('sum:', sum(positives));
}
console.log('Just numbers:');
example([1, 2, 3, 4, 5, -2, 23, -1, -13, 10, -52]);
console.log('With a string:');
// This one won't make it past the "if" statement
example([1, 2, '3', 4, 5, -2, 23, -1, -13, 10, -52]);
console.log('With a boolean:');
// Neither will this one
example([1, 2, false, 4, 5, -2, 23, -1, -13, 10, -52]);