Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我应该在JavaScript的短块/函数中定义变量吗?_Javascript_Html - Fatal编程技术网

我应该在JavaScript的短块/函数中定义变量吗?

我应该在JavaScript的短块/函数中定义变量吗?,javascript,html,Javascript,Html,我知道定义变量在遇到大的块时很有用。但在短块/函数中,变量只使用一次,这似乎只是浪费字节。这是一个例子。这样做不是更好吗: function SelectInput() { document.getElementById("input").select(); 与此相反: function SelectInput () { var input = document.getElementById ("input"); inp

我知道定义变量在遇到大的块时很有用。但在短块/函数中,变量只使用一次,这似乎只是浪费字节。这是一个例子。这样做不是更好吗:

function SelectInput() {
            document.getElementById("input").select();
与此相反:

 function SelectInput () {
            var input = document.getElementById ("input");
            input.select ();
        }

只要有一个表达式需要多次求值,就应该使用变量。您还可以使用变量,通过描述性地命名,并将大型链分解为合理的块,从而提高可读性

不管这个街区有多大


在您的例子中,变量
input
是非常无用的,很明显
document.getElementById(“input”)
返回一个/输入。

在这种情况下,正如您所说,这是在浪费时间和字节。但是,在一些短的块中,使用变量可能会有所帮助:

function changeStyle() {
    var style = document.getElementById('image').style; //an extra variable here would help us check whether there is an element with id 'image' or not.
    style.width = 200;
    style.height = 100;
}

即使在三行代码中,定义
style
也很有用,因为访问DOM比创建一个简单变量要慢。在这里,正如我在注释中所指出的,您应该创建一个变量来存储getElementById()方法的结果,因为它可以返回null。

这里的问题到底是什么……避免在小函数中定义变量不是更好吗?问题是,您的目标是什么。你想要一个好的、可读的代码,还是需要一个短的(出于某种原因)和脏的代码?一个尽可能短的、好的、可读的代码。是的,我所说的短块/函数是指那些变量只使用一次的块/函数——就像上面的一个。在这种情况下,这取决于你对元素的存在有多确定。如果
getElementById(id)
为null,将引发异常。