【问题标题】:how do I use values from an array inside a function in another function?如何在另一个函数的函数内使用数组中的值?
【发布时间】:2019-05-04 02:49:42
【问题描述】:

我在 Javascript 中创建了一个将十进制数转换为二进制数的函数,我使用一个数组来存储二进制数,并让函数返回数组,我想要的是,我如何获取该数组的值和在函数之外或在另一个函数中使用它?

这就是我说的函数,我想要的那个数组叫做numArray。

        function decimalToBinary(Num) {
    	let bits = ''; 
    	let rem = Num; 
    	for(let i = 7; i >= 0; i--) {
    		let divisor = Math.pow(2, i); 
    		let bitValue = Math.floor(rem / divisor);
    		bits = bits + bitValue; 
    		rem = rem % divisor; 
    	}
    	
    	let numArray = []; 
    	
    	for(let i = 0; i < bits.length; i++){
    		let bit = bits.charAt(i);
    		let binaryNums = parseInt(bit);
    		numArray.push(binaryNums); 
    	}
    	
    	return numArray; 

    	}

    /*
    what I want to do is to use a specific value from inside that array 
    and use inside a second function, and then use if-statement to get the 
    result I want
    */

    function second() {
        //if-statement 
        if(numArray[2] === 1){
        //do something
        }else{
        //do something else
        }

      }

【问题讨论】:

  • 您可以在两个函数都可以访问的范围内定义数组。
  • 我该怎么做?您的意思是在函数之外定义函数,以便在两个函数中都可以访问它?
  • 可以在外面定义变量。
  • 我建议不要使用这种方法 - 您最终会在多个位置修改数组内容,这将导致难以管理的错误。您的函数似乎有点明智,它返回您想要的数组。因此,请向我们展示一些背景信息。你是如何使用这个功能的?
  • 我编辑了上面的代码,因此您可以看到一个示例,说明我想如何在第二个函数中使用数组的值

标签: javascript arrays function binary


【解决方案1】:
var binary = [] ;
function decimalToBinary(Num) {
    // do some logic push the output in binary
return binary; 
}

function second(argument){
 //Here you can access the binary
}

P.S:- 这是反模式,如果你更新你的问题,我可以告诉你更多的方法。

【讨论】:

  • 虽然在技术上是正确的,但我认为这种方法在我能想到的大多数情况下都是有害的。 1) 在函数中操作外部作用域,2) 从外部作用域返回值通常不是一个好主意。
  • @SamiHult 我知道这是反模式。但只有当操作人员没有具体说明他将使用第二个函数或他如何调用第二个函数时,我才能回答这个问题
  • 我同意,所以让我们等待更新,然后再回到这个问题。
猜你喜欢
  • 2014-03-24
  • 1970-01-01
  • 1970-01-01
  • 2022-12-11
  • 1970-01-01
  • 1970-01-01
  • 2015-12-24
  • 2019-09-11
  • 1970-01-01
相关资源
最近更新 更多