[英]JavaScript Split Array with comma
我有以下數組point []與:
11,133,3032,144,412,44,43,44,444,54,22,44,11,163,480,344
我正在嘗試每4拆分一個。
我想要類似的東西:
point[0] = 11,133,3032,144
point[1] = 412,44,43,44
point[2] = 444,54,22,44
point[3] = 11,163,480,344
我經常嘗試:
str.split(",", 4)
; 但最后還有逗號和大小問題。
我該如何進行?
謝謝!
您可以通過splice
數組來做到這一點。
var str = "11,133,3032,144,412,44,43,44,444,54,22,44,11,163,480,344";
var arr = str.split(','), result = [];
while(arr.length > 0) {
result.push(arr.splice(0, 4));
}
如果您使用數組而不是字符串,則可以只使用最后三行。
如果您嘗試從字符串中獲取子字符串,也可以使用正則表達式進行操作。
str = "11,133,3032,144,412,44,43,44,444,54,22,44,11";
points = [];
while((match = /([0-9]+,){3}[0-9]+/.exec(str)) != null){
points.push(match[0]);
str = str.replace(/([0-9]+,){3}[0-9]+,*/, "");
}
if (str!="") //if last substring has less than 4 elements
points.push(str);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.