简体   繁体   中英

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? 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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