You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:05:12