简体   繁体   English

自包含函数的JavaScript数组访问自我索引

[英]JavaScript Array of Self-Contained Functions access to index of self

Given an array of self-contained JavaScript functions is there a way to access their respective indexes from within the function code? 给定一系列独立的JavaScript函数,是否可以从函数代码中访问它们各自的索引? I would like to avoid having to hard-code those indexes in the function code: 我想避免必须在功能代码中对那些索引进行硬编码:

var testArr = [
(function(){return 0})(),
(function(){return 'how to return/access ARRAY INDEX (=1)??'})()
]


console.log(testArr[0]) // 0
console.log(testArr[1]) // how to return/access ARRAY INDEX (=1)??

Having analyzed different options I think this one is the most appropriate (without immediate invocation of self-contained function + passing array index into function arguments) 分析了不同的选项后,我认为这是最合适的(无需立即调用自包含函数+将数组索引传递给函数参数)

var testArr = [
(function(idx){return idx}),
(function(idx){return idx * 2})
]

console.log(testArr[0](0)) // 0
console.log(testArr[1](1)) // 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM