的forEach()和应用()为二维数组的JavaScript方法 [英] forEach() and Apply() methods for two dimensional array javascript
问题描述
我有一个数组的元素也是数组,每个包含3个元素。我想打电话给函数calcMe(A,B,C){...}
我的每个使用的forEach主阵列中的元素( )
方法,但我真是一头雾水,不知道如何得到它的工作。
ARR = [[1,5,4],[8,5,4],[3,4,5],[1,2,3]
功能calcMe(A,B,C){...}
arr.forEach(calcMe.Apply(-----,-----));
我如何通过每个内部数组的元素作为参数使用)我的功能应用(
?
首先, calcMe
似乎并没有返回的函数,这样你就可以不通过其返回值的forEach
。
我猜你想要的东西,像
VAR ARR = [\r
[1,5,4],\r
[8,5,4]\r
[3,4,5],\r
[1,2,3]\r
]\r
\r
功能calcMe(A,B,C){\r
VAR pre =的document.getElementById('pre')\r
pre.innerHTML + ='calcMe参数:'+ A +,+ B +,+ C +&所述峰; br />中;\r
}\r
\r
arr.forEach(功能(EL,指数){\r
//也可以使用`ARR [指数]`,而不是埃尔\r
calcMe.apply(这一点,EL);\r
});
\r
< pre ID ='pre'>&LT ; / pre>
\r
有关票友版本,可以绑定 Function.prototype.apply的
效仿创建一个函数,像我上面那样。
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 + "<br/>";
}
arr.forEach(function(el, index) {
// Could also use `arr[index]` instead of el
calcMe.apply(this, el);
});
<pre id='pre'></pre>
For a fancier version, you can bind Function.prototype.apply
to emulate creating a function like I did above.
这篇关于的forEach()和应用()为二维数组的JavaScript方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!