【发布时间】:2015-03-10 18:10:38
【问题描述】:
我有一个字符串,我想将其转换为一个数组,将字符串中的每 3 个字符作为该数组中的一个项目。例如“
var theString = "hello there!"
// the resulting array will look like this
["hel", "lo ", "the", "re!"]
【问题讨论】:
标签: javascript arrays
我有一个字符串,我想将其转换为一个数组,将字符串中的每 3 个字符作为该数组中的一个项目。例如“
var theString = "hello there!"
// the resulting array will look like this
["hel", "lo ", "the", "re!"]
【问题讨论】:
标签: javascript arrays
你可以试试这样的:
var theString = "hello there!";
var arr = [];
for (var i = 0; i < theString.length; i+=3) {
arr.push(theString.substring(i, i+3));
}
【讨论】:
arr 返回为:["hel", undefined × 2, "lo ", undefined × 2, "the", undefined × 2, "re!"]
Array.push(),它会将值添加到arr[] 的末尾。我更新了我的答案以反映这一点。