JavaScript中二维数组的forEach()和Apply()方法 [英] forEach() and Apply() methods for two dimensional array in JavaScript

查看:222
本文介绍了JavaScript中二维数组的forEach()和Apply()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,其元素也是数组,每个数组包含三个元素.我想使用forEach()方法为主数组的每个元素调用function calcMe(a,b,c){...},但是我非常困惑,不知道如何使它工作.

I have an array whose elements are also arrays, each containing three 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(-----, -----));

如何使用Apply()将内部数组的每个元素作为参数传递给函数?

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

推荐答案

首先,calcMe似乎没有返回函数,因此您无法将其返回值传递给forEach.

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

我猜你想要类似的东西

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  + "<br/>";
}

arr.forEach(function(el, index) {
  // Could also use `arr[index]` instead of el
  calcMe.apply(this, el);
});

<pre id='pre'></pre>

对于更高级的版本,您可以绑定Function.prototype.apply 来模拟创建函数,就像我上面所做的那样.

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

这篇关于JavaScript中二维数组的forEach()和Apply()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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