如何识别数组中的任意字符串?数组求和场景的代码实现需求
Alright, let's solve this problem where we need to sum three elements in an array—but only if all elements are numbers. If there's any string in the array, we return "not valid". I'll cover implementations in a few popular languages so you can pick what fits your use case.
First up, JavaScript. We can use typeof to check each element's type, and the some() method to quickly spot if any element is a string. Here's the code:
function sumValidArray(arr) { // Check if any element is a string if (arr.some(item => typeof item === 'string')) { return "not valid"; } // Sum all elements if they're all numbers return arr.reduce((total, num) => total + num, 0); } // Test cases console.log(sumValidArray([96, ".!asd", 182])); // Output: "not valid" console.log(sumValidArray(["@#$%", 5, 43])); // Output: "not valid" console.log(sumValidArray([64, "bd", 48])); // Output: "not valid" console.log(sumValidArray([10, 20, 30])); // Output: 60
The some() method stops checking as soon as it finds a string, which makes it efficient. If no strings are found, we use reduce() to calculate the total sum.
In Python, we can use isinstance() to check element types and any() to detect if there's any string in the array. Here's how it works:
def sum_valid_array(arr): # Check for any string elements if any(isinstance(item, str) for item in arr): return "not valid" # Sum the numbers if all are valid return sum(arr) # Test cases print(sum_valid_array([96, ".!asd", 182])) # Output: "not valid" print(sum_valid_array(["@#$%", 5, 43])) # Output: "not valid" print(sum_valid_array([64, "bd", 48])) # Output: "not valid" print(sum_valid_array([10, 20, 30])) # Output: 60
any() returns True immediately when it hits a string, triggering our invalid response. If all elements are numeric, Python's built-in sum() handles the addition cleanly.
For Java, since arrays are strongly typed, we'll use an Object[] (to hold both numbers and strings). We'll loop through each element to check for strings, then sum the numbers if everything is valid:
public class ArraySumValidator { public static String sumValidArray(Object[] arr) { // Check each element for string type for (Object item : arr) { if (item instanceof String) { return "not valid"; } } // Calculate the sum of numeric elements int total = 0; for (Object item : arr) { total += ((Number) item).intValue(); } return String.valueOf(total); } public static void main(String[] args) { System.out.println(sumValidArray(new Object[]{96, ".!asd", 182})); // Output: "not valid" System.out.println(sumValidArray(new Object[]{"@#$%", 5, 43})); // Output: "not valid" System.out.println(sumValidArray(new Object[]{64, "bd", 48})); // Output: "not valid" System.out.println(sumValidArray(new Object[]{10, 20, 30})); // Output: "60" } }
We loop through the array twice here: first to check for strings, then to sum the numbers. If any element is a String, we return the invalid message right away.
内容的提问来源于stack exchange,提问作者user9279766

