• Index

#### map/reduce

Last updated: ... / Reads: 15643370 Edit

### map

``````'use strict';

function pow(x) {
return x * x;
}
----
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var results = arr.map(pow); // [1, 4, 9, 16, 25, 36, 49, 64, 81]
console.log(results);
``````

``````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
``````

``````var arr = [123];
arr.reduce(function (x, y) {
return x + y;
}, 0); // 123
``````

``````'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) {
console.log('测试通过!');
}
else {
console.log('测试失败!');
}
``````

``````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) {
console.log('请勿使用parseInt()!');
} else if (string2int.toString().indexOf('Number') !== -1) {
console.log('请勿使用Number()!');
} else {
console.log('测试通过!');
}
}
else {
console.log('测试失败!');
}
``````

### 练习

``````'use strict';

function normalize(arr) {
----
return [];
----
}

// 测试:
console.log('测试通过!');
}
else {
console.log('测试失败!');
}
``````

``````'use strict';

var arr = ['1', '2', '3'];
var r;
----
r = arr.map(parseInt);
----
console.log(r);
``````