我试图使用递归函数将多维数组展平为一维数组。
我的单维数组elements
正在返回undefined
JS Bin,我的例子是here。
HTML:
<span class="one"></span>
<span class="one"></span>
<span class="two"></span>
JS:
// elements collection
var elementsCollection = [];
var elements = [];
/* toSingle
* convert mutlidimensional array to one dimensional array (i.e. flatten)
*
* @param ec - array
*/
function toSingle (ec) {
for (var i = 0; i < ec.length; i++) {
if (ec[i].length) {
toSingle(ec[i])
}
else {
elements.push(ec[i]);
}
}
}
// get elements by their HTML class name
var buttons = [ 'one', 'two' ];
// collect elements from class names
for (var i = 0; i < buttons.length; i++) {
elementsCollection.push(document.getElementsByClassName(buttons[i]));
}
// convert multiDimensional array to one dimensional
elements = toSingle(elementsCollection);
// log
console.log(elements); // undefined
答案 0 :(得分:1)
您需要返回数组elements
。
建议将该数组elements
放入函数toSingle
/* toSingle
* convert mutlidimensional array to one dimensional array (i.e. flatten)
*
* @param ec - array
*/
function toSingle(ec) {
var elements = [];
for (var i = 0; i < ec.length; i++) {
if (ec[i].length) {
elements = elements.concat(toSingle(ec[i]));
} else {
elements.push(ec[i]);
}
}
return elements
}
// get integers, first, previous, next, last buttons by their HTML class name
var buttons = ['one', 'two'];
// elements collection
var elementsCollection = [];
// collect elements from class names
for (var i = 0; i < buttons.length; i++) {
elementsCollection.push(document.getElementsByClassName(buttons[i]));
}
// convert multiDimensional array to one dimensional
var elements = toSingle(elementsCollection);
// log
console.log(elements);
<span class="one"></span>
<span class="one"></span>
<span class="two"></span>
答案 1 :(得分:0)
首先,您可以使用querySelectorAll()来避免无用的循环(并将数组作为参数传递,因为它将被强制转换为String)。
其次,如果您不介意使用es6的功能,只需将接收到的对象分散在一个数组中即可。 只留下两行:
(另请注意,尽管在您的示例中似乎并非如此,但使用@ Ele的解决方案时,如果您的元素包含两个或更多类,则必须删除重复项)
var buttons = ['.one', '.two','.three'];
var elements =[...document.querySelectorAll(buttons)];
console.log(elements);
&#13;
<span class="one two"></span>
<span class="one two three"></span>
<span class="two one four"></span>
<span class="one"></span>
<span class="two three"></span>
&#13;