这是我在 github 上发现的一个原生 js 挑战项目, 由于是 js 小白, 希望通过这次的项目加深对 js 的理解
第 4 天主要是一些关于数组的操作
- *filter
- map
- sort
- reduce
新的调试方式
以往我们习惯于用 console,log() 来输出, 本次练习出现了 console.table() 这种新方式, 将数据以表格的形式显示
效果图
js 数组的操作 (重点)
filter
正如英文名一样, 这是一个过滤器, filter() 方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素 MDN 中给出的例子是这样子的:
- function isBigEnough(value) {
- return value >= 10;
- }
- var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
- // filtered is [12, 130, 44]
- // ES6 way
- const isBigEnough = value = >value >= 10; // 类似 function(value){return value>=10}
- let[...spraed] = [12, 5, 8, 130, 44]; //... 代表不定参数
- let filtered = spraed.filter(isBigEnough);
- // filtered is [12, 130, 44]
该例子是筛选出数组中大于 10 的元素
map
map() 方法创建一个新数组, 其结果是该数组中的每个元素都调用一个提供的函数后返回的结果 (即把数组中的每个元素进行处理后, 返回一个新的数组)
- // 使用三个参数
- const numbers = [1, 2, 3, 4, 5];
- let arr = numbers.map((currentValue, index, array) = >{
- console.log(`currentValue = `, currentValue);
- console.log(`index = `, index);
- console.log(`array = `, array);
- return currentValue * 2;
- },
- numbers);
- console.log(`arr`, arr);
- let numbers = [1, 5, 10, 15];
- let doubles = numbers.map((x) = >{
- return x * 2;
- });
- // doubles is now [2, 10, 20, 30]
- // numbers is still [1, 5, 10, 15]
- let numbers = [1, 4, 9];
- let roots = numbers.map(Math.sqrt);
- // roots is now [1, 2, 3]
- // numbers is still [1, 4, 9]
- // 即 map() 不改变原数组
- sort
sort() 是一种冒泡排序, 默认排序顺序是根据字符串 Unicode 码点
- var fruit = ['cherries', 'apples', 'bananas'];
- fruit.sort();
- // ['apples', 'bananas', 'cherries']
- var scores = [1, 10, 21, 2];
- scores.sort();
- // [1, 10, 2, 21]
- // 注意 10 在 2 之前,
- // 因为在 Unicode 指针顺序中 "10" 在 "2" 之前
- var things = ['word', 'Word', '1 Word', '2 Words'];
- things.sort();
- // ['1 Word', '2 Words', 'Word', 'word']
- // 在 Unicode 中, 数字在大写字母之前,
- // 大写字母在小写字母之前.
如果想要升序或者降序, 我们需要价格比较函数, 例如
- function compareNumbers(a, b) {
- return a - b;
- }
- reduce
reduce 这是一个归并数组的方法, 它接受一个函数作为参数 (这个函数可以理解成累加器), 它会遍历数组的所有项, 然后构建一个最终的返回值, 这个值就是这个累加器的第一个参数, 第二个参数为可选项, 其值用于第一次调用 callback 的第一个参数如果没有设置初始值, 则将数组中的第一个元素作为初始值空数组调用 reduce 时没有设置初始值将会报错
- var total = [0, 1, 2, 3].reduce(function(sum, value) {
- return sum + value;
- }, 0);
- // total is 6
以上就是我在 day4 中学到的知识, 这里我参考了 soyaine 的中文指南
来源: http://www.jianshu.com/p/a7986ddcd621