论坛首页 Web前端技术论坛

<JavaScript The Definitive Guide 5th>的一个错误

浏览 1782 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-04-28  

第八章的Flexsum的例子,书上的代码如下:

function flexisum(a) {
    var total = 0;
    for(var i = 0; i < arguments.length; i++) {
        var element = arguments[i];
        if (!element) continue;  // Ignore null and undefined arguments

        // Try to convert the argument to a number n,
        // based on its type
        var n;
        switch(typeof element) {
        case "number":
            n = element;                  // No conversion needed here
            break;
        case "object":
            if (element instanceof Array) // Recurse for arrays
                n = flexisum.apply(this, element);
            else n = element.valueOf();   // valueOf method for other objects
            break;
        case "function":
            n = element();                // Try to invoke functions
            break;
        case "string":
            n = parseFloat(element);      // Try to parse strings
            break;
        case "boolean":
            n = NaN;                      // Can't convert boolean values
            break;
        }

        // If we got a valid number, add it to the total.
        if (typeof n == "number" && !isNaN(n)) total += n;
        // Otherwise report an error
        else throw new Error("sum(): can't convert " + element + " to number");
    }
    return total;
}

 

我调试后发现这个apply应用的不太对,应该是call。我将这个例子改进了一下(当然也改动了一下),代码如下:

<html>
	<head>
		<title>
		</title>
	</head>
	<body>
		<script language="javascript">
			function flexsum(arr) {
				var rst = 0;
				if (arr instanceof Array || typeof arr == "object" && "length" in arr) {
					for (var i = 0 ; i < arr.length; ++i) {
						if (!arr[i]) {
						   	continue;
						}
						else {
							var n;
							if (typeof arr[i] == "number") {
								n = arr[i];
							}
							else if (typeof arr[i] == "function") {
								n = arr[i]();
							}
							else if (typeof arr[i] == "string") {
								n = parseFloat(arr[i]);
							}
							else if (typeof arr[i] == "boolean") {
								if (arr[i]) {
									n = 1.0;
								}
								else {
									n = 0.0;
								}
							}
							else if (typeof arr[i] instanceof Array || typeof arr[i] == "object" && "length" in arr[i]) {
								n = flexsum.call(this, arr[i]);
							}
							else { // typeof arr[i] == "object"
								n = arr[i].valueOf();
							}

							if (typeof n == "number" && !isNaN(n)) {
								rst += n;
							}
						}

					}
					return rst;
				}
				else {
					throw new Error("The argument " + arr.toString() + "is not a Array or Arraylike object!");
				}
			}
			var arr1 = [1,2,3];
			document.write(flexsum(arr1) + "<br>");
			var arr2 = [1,2,3,"4", [5,6,7]];
			document.write(flexsum(arr2) + "<br>");
		</script>
	</body>
</html>

 

   发表时间:2009-04-29  
什么地方不对了,lz说说啊
0 请登录后投票
论坛首页 Web前端技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics