[英]How to print elements from array with recursion in javascript
Array.prototype.myForEach = function(element) { for (var i = 0; i < this.length; i++) { element(this[i], i, this); } }; var forArr = ['8', '17', '25', '42','67']; forArr.myForEach(function(exm){ console.log(exm); });
我在表格里写了。 你能帮忙把它翻译成递归吗?
Array.shift将在这里完成技巧
var forArr = ['8', '17', '25', '42', '67']; function recursivearray(array) { if (array.length > 0) { console.log(array.shift()); recursivearray(array); } } recursivearray(forArr);
var forArr = ['8', '17', '25', '42','67']; var recursive_function = function(array){ if(array.length > 0){ console.log(array[0]); recursive_function(array.slice(1)) } } recursive_function(forArr)
您可以将函数调用与附加参数一起用于实际索引。
Array.prototype.myForEach = function (fn, thisArg, i = 0) { if (!(i in this)) { return; } fn.bind(thisArg)(this[i], i, this); this.myForEach(fn, thisArg, i + 1); }; function showValues(v, i, a) { console.log(v, i, JSON.stringify(a)); } [99, 100, 101, 102].myForEach(showValues);
此代码应在 JS 中使用递归打印元素:
var foo = ["8", "17", "25", "42", "67"];
const product = (arr) => {
if (!arr.length) return 1;
return product(arr.slice(1)) * arr[0];
};
console.log(product(foo));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.