JavaScript将变量传递给函数名称

时间:2019-01-26 15:34:27

标签: javascript arrays object

我正在尝试创建一个简单的动画功能循环。我将它们的名称存储在数组中,并且能够通过单击事件将每个对象作为字符串注销。但是我似乎无法调用该事件的相应功能

我尝试这样做,但是出现错误nt [rt]不是函数

arrAnimations[activeScene]()

我从类似问题的堆栈溢出中尝试了许多方法,例如创建这样的辅助函数

myFunction = function(){};   
var arrAnimations = {italy: myFunction};

arrAnimations['activeScene']();//executes the function

还有这个

var tmp = arrAnimations[activeScene]
window[tmp]

代码如下:

var arrAnimations = [
  'italy',
  'czech',
  'russia'
]

var activeScene = 0;

document.getElementById('animate').addEventListener("click",
  function incNumber() {
      if (activeScene < arrAnimations.length - 1) {
          activeScene++;
      } else if (activeScene = arrAnimations.length - 1) {
          activeScene = 0;
      }
      // console.log(arrAnimations[activeScene])
  }
)

function italy() { console.log('italy') }

function czech() { console.log('czech') }

function russia() { console.log('russia') }
<div id="animate">Animate</div>

4 个答案:

答案 0 :(得分:1)

该数组可以存储实际的函数本身,而不是存储函数名称。

function italy()  { console.log('italy') }
function czech()  { console.log('czech') }
function russia() { console.log('russia') }

var arrAnimations = [ italy, czech, russia ]

然后在数组中找到该项目,并调用它:

var activeScene = 0;
arrAnimations[activeScene]()

堆栈摘要中的演示

function italy()  { console.log('italy') }
function czech()  { console.log('czech') }
function russia() { console.log('russia') }

var arrAnimations = [ italy, czech, russia ]

var index = 0;

function callNextFunction() {
    index = index >= arrAnimations.length - 1 ? 0 : index + 1
    
    arrAnimations[index]()
}

var btn = document.getElementById('animate')
btn.addEventListener("click", callNextFunction)
<button id="animate">Animate</button>

答案 1 :(得分:1)

在您的注释行中:

console.log(arrAnimations[activeScene])

您试图在数组上调用一个不存在的方法。它是一个字符串数组。相反,您需要获取字符串值,然后使用该值在窗口上调用方法。

window[arrAnimations[activeScene]]();

尽管如此,我将使您的代码更简单并使用lambda函数,并避免使用两个if语句,请尝试以下操作:

<div id="animate">Animate</div>

<script>
    var arrAnimations = [
        () => console.log('italy'),
        () => console.log('czech'),
        () => console.log('russia')
    ]

    var activeScene = 0;

    document.getElementById('animate').addEventListener('click', () => {

        arrAnimations[activeScene]();

        activeScene++;
        activeScene = activeScene % arrAnimations.length;
    });
</script>

答案 2 :(得分:1)

italy = () => console.log('italy')
czech = () => console.log('czech')
russia = () => console.log('russia') 

如果是函数数组:

let arrAnimationsAsFunctions = [ italy , czech , russia];
arrAnimationsAsFunctions.forEach(animation => animation())

如果是字符串数组:

let arrAnimationsAsStrings = [ 'italy' , 'czech' , 'russia' ];
arrAnimationsAsStrings.forEach(animation => eval(animation)())

使用eval将字符串作为JS代码运行

答案 3 :(得分:0)

这是您想要的吗?

foo = () => console.log('foo')
bar = () => console.log('bar')
baz = () => console.log('baz')

fns = {
  foo,
  bar,
  baz
}

Object.keys(fns).forEach(fn => fns[fn]())

fns['foo']()
fns['bar']()

注意:至少在Javascript中,您不能将字符串强制转换为这样的函数:

let fn = () => {}
let foo = 'fn'
foo()  // X
// foo is a string, not a function, It is just a coincidence that the content of the string is same with the function's name