简体   繁体   English

为什么不将变量声明为函数的参数?

[英]Why not declaring a variable as an argument of a function?

I don't see that in any shorthand technique or stackOverflow questions..then I wonder if the following can be a shorthand technique. 我在任何速记技术或stackOverflow问题中都没有看到这一点,那么我想知道以下内容是否可以作为速记技术。

Imagine I have a function which I know there is exactly 1 argument that will be passed to it : 想象一下,我有一个函数,我知道将有1个参数传递给它:

function myFunc(arr) {
  var i;
  for(i = 0; i < arr.length; i++ ) {
    if(arr[i] === 3) {return true;}
  }
}

Is it a good practice in that case to write : 在这种情况下,写这样的好习惯吗?

function myFunc(arr, i) {
  for(i = 0; i < arr.length; i++ ) {
    if(arr[i] === 3) {return true;}
  }
}

I know that in most case we only save 4 bytes and this represent a very small improvement but sometimes for a short function it can be more readable without wasting 1/2 lines just to declare variables. 我知道,在大多数情况下,我们只保存4个字节,这仅是很小的改进,但有时对于短函数而言,它更易读,而不会浪费1/2行来声明变量。

Edit: also I want to declare i in the scope of the function and not in the for loop sinc I want to be able to reuse it. 编辑:我也想在函数范围内声明i,而不是在for循环sinc中声明我希望能够重用它。

You would only do this if you were going to actually use i in the for loop. 仅当您要在for循环中实际使用i ,才需要这样做。

eg: 例如:

function myFunc(arr, i) {
    for(i; i < arr.length; i++ ) {
        arr[i];
    }
}

// Why you would do this though, is another matter (and bizarre)
myFunc(anArray, 9); 

Instead, it would be better to do: 相反,最好这样做:

function myFunc(arr) {
    for(var i = 0; i < arr.length; i++ ) {
        arr[i];
    }
}

and not worry about 4 bytes... 不用担心4个字节...

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

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