本文介绍了JavaScript的递归阵列压扁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我锻炼,想写一个递归阵列功能扁平化。在code放在这里:
I'm exercising and trying to write a recursive array flattening function. The code goes here:
function flatten() {
var flat = [];
for (var i = 0; i < arguments.length; i++) {
if (arguments[i] instanceof Array) {
flat.push(flatten(arguments[i]));
}
flat.push(arguments[i]);
}
return flat;
}
问题是,如果我通过有数组或嵌套数组我得到的最大调用堆栈大小超过错误。我在做什么错了?
The problem is that if I pass there an array or nested arrays I get the "maximum call stack size exceeded" error. What am I doing wrong?
推荐答案
问题是你如何通过阵列的处理,如果该值是一个数组,那么你继续调用它导致一个无限循环
The problem is how you are passing the processing of array, if the value is an array then you are keep calling it causing an infinite loop
function flatten() {
var flat = [];
for (var i = 0; i < arguments.length; i++) {
if (arguments[i] instanceof Array) {
flat.push.apply(flat, flatten.apply(this, arguments[i]));
} else {
flat.push(arguments[i]);
}
}
return flat;
}
演示:
这篇关于JavaScript的递归阵列压扁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!