本文介绍了递归地反转数组中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在javascript中编写一个递归函数,该函数返回一个数组,其元素反转.这段代码会产生以下错误:
I want to write a recursive function in javascript that returns an array with its elements reversed. This code generates the following error:
function reverseArray (toBeReversed){
var reversed = [];
function reverser (toBeReversed){
if (toBeReversed.length == 1)
reversed.push(toBeReversed[0]);
else {
reversed.push(toBeReversed.lastOfIndex(0)); //error on this line
reverser(toBeReversed.slice(-1));
}
}
reverser(toBeReversed);
return reversed;
}
推荐答案
lastOfIndex不是一个函数,您可能希望使用lastIndexOf.这是类似的方法:
lastOfIndex is not a function, you probably mean to use lastIndexOf. here is a similar way:
function reverseArray (toBeReversed){
var reversed = [];
function reverser (toBeReversed){
if (toBeReversed.length !== 0){
reversed.push( toBeReversed.pop() );
reverser( toBeReversed );
}
}
reverser(toBeReversed);
return reversed;
}
这篇关于递归地反转数组中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!