# map/reduce

## map

``````function pow(x) {
return x * x;
}

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
arr.map(pow); // [1, 4, 9, 16, 25, 36, 49, 64, 81]
``````

`map()`传入的参数是`pow`，即函数对象本身。

``````var f = function (x) {
return x * x;
};

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var result = [];
for (var i=0; i<arr.length; i++) {
result.push(f(arr[i]));
}
``````

``````var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
arr.map(String); // ['1', '2', '3', '4', '5', '6', '7', '8', '9']
``````

## reduce

``````[x1, x2, x3, x4].reduce(f) = f(f(f(x1, x2), x3), x4)
``````

``````var arr = [1, 3, 5, 7, 9];
arr.reduce(function (x, y) {
return x + y;
}); // 25
``````

``````'use strict';

function product(arr) {

return 0;

}

// 测试:
if (product([1, 2, 3, 4]) === 24 && product([0, 1, 2]) === 0 && product([99, 88, 77, 66]) === 44274384) {
}
else {
}
``````

``````var arr = [1, 3, 5, 7, 9];
arr.reduce(function (x, y) {
return x * 10 + y;
}); // 13579
``````

``````'use strict';

function string2int(s) {

return 0;

}

// 测试:
if (string2int('0') === 0 && string2int('12345') === 12345 && string2int('12300') === 12300) {
if (string2int.toString().indexOf('parseInt') !== -1) {
} else if (string2int.toString().indexOf('Number') !== -1) {
} else {
}
}
else {
}
``````

## 练习

``````'use strict';

function normalize(arr) {

return [];

}

// 测试:
}
else {
}
``````

``````'use strict';

var arr = ['1', '2', '3'];
var r;

r = arr.map(parseInt);

alert('[' + r[0] + ', ' + r[1] + ', ' + r[2] + ']');
``````

<button id="x-why-parseInt-failed" class="uk-button uk-button-success">原因分析</button>

• parseInt('0', 0); // 0, 按十进制转换

• parseInt('1', 1); // NaN, 没有一进制

• parseInt('2', 2); // NaN, 按二进制转换不允许出现2