简体   繁体   English

如何返回函数变量的值

[英]How to return the value of a function variable

I'm finishing a carousel and I want to separate the codes.我正在完成一个旋转木马,我想分离代码。 I need to return the value of a function variable and I don't understand.我需要返回一个函数变量的值,我不明白。 When I put a value in 'return', it returns, but the value of the variable does not.当我在 'return' 中放入一个值时,它会返回,但变量的值不会。 I'll just post more important parts of the code and try to explain我只会发布代码的更重要部分并尝试解释

This is the first function, which changes images.这是第一个功能,它改变图像。 The function I'm calling is to return the position of the button within the array.我调用的函数是返回数组中按钮的位置。 This array is the 'buttons' variable.该数组是“按钮”变量。

const buttons = document.querySelectorAll('.carousel-button');
function moveSlider() {
  buttons.forEach(element => {
    element.addEventListener('click', (event) => {
        var buttonId;
        var carouselId;
        var btnPosition

        var id = event.target.id;
        buttonPosition(id)
        console.log(buttonPosition())
...

The Function I'm calling up there我在那里调用的函数

function buttonPosition(id){
  var position;
  for($i = 0; $i < buttons.length; $i++){
      if(id == buttons[$i].id){
          position = $i;
      }
  }

  return position;
}

Why does the variable value return 'undefined'?为什么变量值返回“未定义”?

You are first calling the method with the parameter "id".您首先使用参数“id”调用该方法。 But when you you use console.log your calling the method again but without the parameter.但是当您使用 console.log 时再次调用该方法但没有参数。 You should store the returned value of the function in a variable and then work with the or for example output the variable.您应该将函数的返回值存储在变量中,然后使用或例如输出变量。

var yourReturnValue = buttonPosition(id)
console.log(yourReturnValue)

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

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