JavaScript 递归 [英] JavaScript Recursion

查看:39
本文介绍了JavaScript 递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人愿意用通俗易懂的语言逐步解释这个程序(取自书籍教程)以帮助我理解递归吗?

Would someone be kind enough to explain this program (taken from a book tutorial) step by step in plain language to help me understand recursion?

var reverseArray = function(x,indx,str) {
return indx == 0 ? str : reverseArray(x, --indx, (str+= " " + x[indx]));;
}

var arr = new Array('apple', 'orange', 'peach', 'lime');
var str = reverseArray(arr,arr.length,"");
alert(str);

var arr2 = ['car','boat','sun','computer'];
str = reverseArray(arr2,arr2.length."");
alert(str);

推荐答案

以下就够了吗?

// declare a variable which is to be the function for reversing the array
var reverseArray = function(x,indx,str) {
// check if the index has reached zero. if it did, return the concatenated string,
// else concatenate the string with the next item in the array at the current index.
// for each subsequent call to the function, the index is decreased by one, working 
// the array backwards.
return indx == 0 ? str : reverseArray(x, --indx, (str+= " " + x[indx]));;
}

// declare an array of fruit
var arr = new Array('apple', 'orange', 'peach', 'lime');
// declare a variable and assign it's value to the result of the recursive function,
// sending through the fruit array, the amount of items in it and an empty string as
// parameters to the function.
var str = reverseArray(arr,arr.length,"");
// show a dialogue box with the result of the function
alert(str);

// do the same as in the fruit example...
var arr2 = ['car','boat','sun','computer'];
str = reverseArray(arr2,arr2.length."");
alert(str);

这篇关于JavaScript 递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆