这个Javascript函数参数在做什么?

时间:2016-02-21 14:03:50

标签: javascript syntax

考虑以下代码(为清楚起见缩短了):

Vertices.chamfer = function(vertices, radius, quality, qualityMin, qualityMax) {
    radius = radius || [8];

    if (!radius.length)
    radius = [radius];
};

我将第一部分读作(伪代码):

if (radius array passed to function) then
  radius = radius
else
  radius = [8] // new array, single element of value 8
end if

但我没有得到第二个表达式(if(!radius.length) radius = [radius]部分)。

有人可以向我解释一下吗?

4 个答案:

答案 0 :(得分:1)

    Vertices.chamfer = function(vertices, radius, quality, qualityMin, qualityMax) {
            // Set the radius to the value passed in. 
            // If the value passed in is undefined, set the radius to an
            // array containing 8 (the "default")
            radius = radius || [8];

            // If radius isn't an array (i.e. length is 0 which evaluates to false), 
            // make it an array.
            if (!radius.length)
            radius = [radius];
        };

答案 1 :(得分:1)

此处使用的概念称为 duck typing - 即通过查找某些特征属性/方法的存在(或不存在)来检查变量的类型。此代码的作者假设,如果某些内容具有length属性,则它是一个数组,如果没有,则可以通过将其包装在[]中将其转换为数组。

第二部分,使用xx转换为包含x = [x]的单项数组完全正常。

问题是JavaScript中还有其他类型的length,所以这个测试真的不可靠。

例如:"7".length返回1,因此如果您将变量作为字符串而不是数字传递(例如,通过读取<input>字段中的值,很容易犯这个错误)某些东西会破坏期望一个数组但获得一个字符串的行。

另一种length类型是Function(function(a,b){}).length == 2

所以是的,这不是一个真正好的测试,但基本的想法是有道理的。应该使用Array.isArray或其他一些对阵列唯一的属性/方法。

编辑:我还指出radius = radius || [8]构造只有在0参数不允许radius时才可以。

答案 2 :(得分:0)

  

我将第一部分读作(伪代码):

     

if (radius array passed to function) then

radius = radius || [8]检查radius是否虚假,可能根本没有传递(undefined),或者传递为{{1}或者以undefinednull0""或当然NaN传入。

但是,如果没有指定false,它可能会使用[8]

  

但我没有得到第二个表达式(if(!radius.length)radius = [radius]部分)。

如果给出了radius但是是A)没有条目的数组(radius是0,因此是假的),或者B)不是数组(radius.length是{{1因此,我们创建一个数组并使其成为该数组中的第一个条目。

这根本没有强大的验证,很多东西都有radius.length(例如字符串),但这可能是它的意味着什么做。

检查某些内容是否为数组的强大方法是使用Array.isArray,这是在ES5中添加的,可以对过时的引擎(如IE8中的引擎)进行可靠的填充/填充。

答案 3 :(得分:0)

如果导入的半径不是数组且它有值,则返回一个半径值在其中的数组。

如果导入的半径为空,则返回一个数字为8的数组:[8]

然而,在伪代码中,如果导入的半径不是数组,则不会进入if语句。

相关问题