如何修复stringLengths函数,使其返回各传入字符串的长度数组?
Got it, let's figure out why your code is returning an empty array and fix it.
First, looking at your loop: you're starting at i=1 instead of i=0. The arguments object is zero-indexed, so when you start at 1, you're skipping the first argument entirely. And if you ever call the function with fewer than 2 arguments, the loop won't run at all, giving you an empty array.
Here's how to fix your existing code by adjusting the loop start index:
function stringLengths(str1, str2, str3, str4) { var arr = []; for (var i = 0; i < arguments.length; i++) { arr.push(arguments[i].length); } return arr; }
That will loop through all the arguments passed (from index 0 to the last one) and push each length into the array.
But since your function is explicitly designed to take four string parameters, an even simpler approach is to skip the loop entirely and directly create the array using the parameters themselves:
function stringLengths(str1, str2, str3, str4) { return [str1.length, str2.length, str3.length, str4.length]; }
This is more straightforward and avoids any issues with the arguments object or loop indices.
Both versions will work for your example call: stringLengths('mushroom', 'onion', '', 'garlic') will return [8, 5, 0, 6] as expected. Just a quick note: if you might ever need to handle a variable number of arguments instead of exactly four, the first approach with arguments (fixed to start at 0) is better. But for your specific requirement, the second approach is cleaner.
内容的提问来源于stack exchange,提问作者Kelajatu

