{/* code */}, "3"]; 匿名函数 self 评估为-6ren">
gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:53:45 25 4
gpt4 key购买 nike

假设我有一个数组:

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

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

匿名函数 self 评估为 "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'))

否则我们不能直接执行。函数不知道它们在脚本中的位置,它们不知道它们是否在全局范围、窗口、数组、对象等中。你需要一个中间人或助手,在这种情况下我们可以使用 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()

关于javascript - 我可以从元素内部获取元素的索引吗?大批,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52470918/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com