我可以从元素内部获取元素的索引吗?大批

Can I get the index of an element from inside the element? array

假设我有一个数组:

我可以拥有一个通过调用来告知其位置的元素吗?假设它是一个函数。

var h = ["0", "1", () => { /* code */ }, "3"];

匿名函数的自我计算结果为 "2"

我们可以通过创建函数并覆盖其功能来使用代理。我们还需要在阵列上创建一个代理。这可以通过代理内的代理来完成。一种修改函数,一种修改数组。然后我们可以像调用普通数组函数一样调用它。

// The original function
function TheFunction(idx, arg1) {
  console.log('Index:', idx, '--', 'Argument:', arg1)
  return Math.round(Math.random() * 100000)
}

let h = ["0", "1", TheFunction, "3", TheFunction];

// Create a Proxy on the array
h = new Proxy(h, {
  // Execute when an array item is accessed
  get(target, prop) {
    // Test if the item is a function
    if(typeof target[prop] != 'function') throw new Error('Not a function!')
    // Create a new Proxy on the original function
    return new Proxy(TheFunction, {
      // When the function gets called run this instead of what was actually called
      apply(target, thisArg, arguments) {
        return target(prop, ...arguments)
      }
    })
  }
})

console.log('Result:', h[2]('hello'))
console.log('Result:', h[4]('world'))

否则不能直接执行。函数不知道它们在脚本中的位置,它们不知道它们是否在全局范围、window、数组、对象等。你需要一个中间人或助手,在这种情况下我们可以使用具有第二个参数的 forEach ,该参数是项目的索引。然后您可以像这样将其作为参数传递:

var h = ["0", "1", (idx) => { console.log(idx) }, "3"];

h.forEach((itm, idx) => {
  if(typeof itm == 'function') {
    itm(idx)
  }
})

如果你有一个只有一个函数的数组,你可以使用 findIndex 来完成类似的任务。但是您仍然需要将索引传递给函数以便函数可以使用它:

var h = ["0", "1", (idx) => { console.log(idx) }, "3"];

let idx = h.findIndex(i => typeof i == 'function')
idx > -1 && h[idx](idx)

这不可能的另一个原因是因为函数可以被引用,所以它可以在数组或其他地方使用。正如您在这里看到的,我们有一个函数的引用,以及一个在数组外部调用的函数。调用的函数不知道调用是来自数组还是数组外部。

function TheFunction(idx) {
  console.log(idx)
}

var h = ["0", "1", TheFunction, "3", TheFunction, "123", TheFunction];

h.forEach((itm, idx) => {
  if (typeof itm == 'function') {
    itm(idx)
  }
})

TheFunction()

是的,您可以循环数组并在内部检查元素类型是否为函数:

var h = ["0", "1", () => {}, "3"]

for(var i = 0; i < h.length; i++){
    if(typeof h[i] === 'function'){
        console.log(i)
    }
}

如果是,只需获取元素的索引。