【发布时间】: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