foreach 二维java,的forEach()和应用()为二维数组的JavaScript方法

本文探讨了如何使用JavaScript的forEach()方法遍历包含嵌套数组的主数组,并通过apply()函数将每个子数组的元素作为参数传递给calcMe()函数。作者提供了实例代码,解释了calcMe()函数不返回函数时的处理方式,以及如何使用箭头函数和bind()方法实现此功能。
摘要由CSDN通过智能技术生成

I have an array which elements are also arrays, each containing 3 elements. I want to call the function calcMe(a,b,c){...} for each of the elements of my main array using forEach() method but I got really confused and don't know how to get it to work.

arr = [[1,5,4],[8,5,4],[3,4,5],[1,2,3]]

function calcMe(a,b,c){...}

arr.forEach(calcMe.Apply(-----,-----));

How do I pass each of the inner array's elements as arguments to my function using Apply()?

解决方案

First, calcMe doesn't seem to return a function, so you can't pass its return value to forEach.

I'm guessing you want something like

var arr = [

[1, 5, 4],

[8, 5, 4],

[3, 4, 5],

[1, 2, 3]

]

function calcMe(a, b, c) {

var pre = document.getElementById('pre')

pre.innerHTML += 'calcMe arguments: ' + a +","+ b +","+ c + "
";

}

arr.forEach(function(el, index) {

// Could also use `arr[index]` instead of el

calcMe.apply(this, el);

});

 
 

For a fancier version, you can bind Function.prototype.apply to emulate creating a function like I did above.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值