JavaScript中按逗号分割变量值及解决循环取值异常问题
Let's walk through the problems in your code one by one and get it working correctly.
First Problem: Incorrect Variable Initialization
Your first line has a critical syntax/logic mistake:
var values = Test1,Test2,Test3,Test4,Test5;
This doesn't create a comma-separated string or collection of values like you intended. JavaScript treats this as the comma operator—only the first value (Test1) gets assigned to values, and the rest are ignored (plus you'll get a ReferenceError if Test1/Test2 aren't defined variables).
Fix Options:
- If you meant to create a comma-separated string of those labels, wrap the whole thing in quotes:
var values = "Test1,Test2,Test3,Test4,Test5"; - If
Test1,Test2, etc. are existing variables you want to collect, skip the string entirely and use an array directly:// Replace with your actual variable values var Test1 = "Alpha", Test2 = "Beta", Test3 = "Gamma", Test4 = "Delta", Test5 = "Epsilon"; var values = [Test1, Test2, Test3, Test4, Test5];
Second Problem: Off-by-One Error in the Loop
Your loop condition uses i <= values.length, which causes an off-by-one bug:
for (var i = 0; i <= values.length; i++) { valueList.push(values[i]); }
JavaScript arrays are zero-indexed. If values has 5 elements (length = 5), valid indices range from 0 to 4. When i hits 5, values[5] is undefined, and you'll push that into valueList—resulting in a 6-element array with an undefined last entry.
Fix this by using < instead of <=:
for (var i = 0; i < values.length; i++) { valueList.push(values[i]); }
Full Corrected Code (String Split Version)
Here's the working code if you're starting from a comma-separated string:
var values = "Test1,Test2,Test3,Test4,Test5"; values = values.split(','); var valueList = []; for (var i = 0; i < values.length; i++) { valueList.push(values[i]); } console.log(valueList.length); // Logs 5 console.log(valueList); // Logs ["Test1", "Test2", "Test3", "Test4", "Test5"]
Bonus: Simplify the Code
If you just need to copy the array, you don't even need a loop! Use array methods like the spread operator or slice():
var values = "Test1,Test2,Test3,Test4,Test5".split(','); var valueList = [...values]; // Or values.slice() console.log(valueList.length); // 5 console.log(valueList); // Same as the split array
内容的提问来源于stack exchange,提问作者Sitharth

