回答
您可以使用jQuery.map,這就是如果你有jQuery庫已經加載的路要走。
$.map([1, 2, [3, 4], [5, 6], 7], function(n){
return n;
});
返回
[1, 2, 3, 4, 5, 6, 7]
您可以使用jQuery.map()
:
回調(值,indexOrKey)來處理每個項目 反對的功能。函數的第一個參數是值;第二個參數 是數組或對象屬性的索引或鍵。函數 可以返回任何值以添加到數組中。 返回的數組 將平鋪到結果數組中。在該函數中,這個 引用全局(窗口)對象。
var a = [1, 2, [3, 4], [5, [6, [7, 8]]]];
var b = [];
function flatten(e,b){
if(typeof e.length != "undefined")
{
for (var i=0;i<e.length;i++)
{
flatten(e[i],b);
}
}
else
{
b.push(e);
}
}
flatten(a,b);
console.log(b);
平化功能應該這樣做,而這並不需要jQuery的。只需將所有這些複製到Firebug並運行即可。
這裏是你如何可以使用jQuery扁平化深度嵌套的數組:
$.map([1, 2, [3, 4], [5, [6, [7, 8]]]], function recurs(n) {
return ($.isArray(n) ? $.map(n, recurs): n);
});
返回:
[1, 2, 3, 4, 5, 6, 7, 8]
利用的jQuery.map作爲以及jQuery.isArray。
老問題,我知道,但是...
我發現這個工作的,是快:
function flatten (arr) {
b = Array.prototype.concat.apply([], arr);
if (b.length != arr.length) {
b = flatten(b);
};
return b;
}
最好在''b = ....''代碼中加一個'var'來避免額外的全局變量。 –
要遞歸扁平化的數組,你可以使用本機Array.reduce功能。沒有必要爲此使用jQuery。
function flatten(arr) {
return arr.reduce(function flatten(res, a) {
Array.isArray(a) ? a.reduce(flatten, res) : res.push(a);
return res;
}, []);
}
執行
flatten([1, 2, [3, 4, [5, 6]]])
回報
[ 1, 2, 3, 4, 5, 6 ]
值得注意的是,它的工作原理,但僅適用於現代瀏覽器(除非已被修補) –
,如果你有多個級別使用遞歸:
flaten = function(flatened, arr) {
for(var i=0;i<arr.length;i++) {
if (typeof arr[i]!="object") {
flatened.push(arr[i]);
}
else {
flaten(flatened,arr[i]);
}
}
return;
}
a=[1,[4,2],[2,7,[6,4]],3];
b=[];
flaten(b,a);
console.log(b);
您可以使用Array.prototype.reduce
這在技術上是不Ĵ查詢,但有效的ES5:
var multidimensionArray = [1, 2, [3, 4], [5, 6], 7];
var initialValue = [];
var flattened = multidimensionArray.reduce(function(accumulator, current) {
return accumulator.concat(current);
}, initialValue);
console.log(flattened);
- 1. 如何在PHP中壓扁數組?
- 2. 在PHP中壓扁數組
- 3. 如何在python中壓扁元組
- 4. 壓扁數組在對象中
- 5. 壓扁對象到數組?
- 6. Python壓扁數組內部numpy數組
- 7. AutoMapper:如何壓扁
- 8. 壓扁嵌套數組/在underscore.js對象
- 9. 試圖壓扁數組在numpy
- 10. 壓扁在PowerShell中
- 11. 如何在eclipse中壓扁包?
- 12. 如何在Python中壓扁XML文件
- 13. 如何在紅寶石中壓扁
- 14. 壓扁OCaml中
- 15. 壓扁和重組提交
- 16. 壓扁元組列表
- 17. 壓扁
- 18. 如何從壓扁jsonlite
- 19. 壓扁多維數組遞歸php
- 20. 壓扁和計數1元組
- 21. 壓扁變長數組列表
- 22. 壓扁奇數組結構的JavaScript
- 23. 如何壓扁結構數組的列(由Spark ML API返回)?
- 24. 如何使用Jolt來壓扁n個對象的json數組?
- 25. PHP遞歸收集SimpleXMLElement數據並壓扁數組數組
- 26. XSLT壓扁XML
- 27. 壓扁RDD
- 28. 如何使用python壓扁元組中的項目列表?
- 29. 使用SQL壓扁數據
- 30. 如何壓扁列表[任何]?
當然,這是它在問題中的表述方式,但是,這也只會使一個層次變平。 – phil