ES5新增
forEach
// forEach 返回undefined
var arr = ['Prosper', 'Lee', 'is', ['very', 'very'], 'nice', '!', , null];
// ES6写法
arr.forEach((currentValue, index, array) => {
console.log('arr[' + index + ']=' + array[index] + '==' + currentValue);
console.log(array.join(",").split(",").join(' '));
});
arr.forEach(function (currentValue, index, array) {
console.log('arr[' + index + ']=' + array[index] + '==' + currentValue);
console.log(array.join(",").split(",").join(' '));
})
// this参数
function Counter() {
this.sum = 0;
this.count = 0;
}
Counter.prototype.add = function (array) {
array.forEach(function (entry) {
this.sum += entry;
++this.count;
console.log(this); // this指向Counter,否则指向window
}, this);
};
var obj = new Counter();
obj.add([1, 3, 5, 7]);
console.log(obj.count); // 4 === (1+1+1+1)
console.log(obj.sum); // 16 === (1+3+5+7)
map
// map与上同,不同方法如下 将每次的值存到数组中然后返回成一个新数组
var arr1 = ['1', '2', 3, '4', 5, '6'];
console.log(arr1.map(v => v + '2'));
console.log(arr1.map(v => v + 2));
console.log(arr1.map(v => v * '2'));
// 例1 返回新数组
var kvArray = [{
key: function () {},
value: 10
},
{
key: 'abc',
value: 20
},
{
key: 3,
value: 30
}
];
var reformattedArray = kvArray.map(function (obj) {
var rObj = {};
rObj[obj.key] = obj.value;
return rObj;
});
console.log(reformattedArray); // [{function () {}: 10},{abc: 20},{3: 30}]
// 例2 两种结果相同
"Hello World".split('').map(function(x) {
return x;
})
Array.prototype.map.call("Hello World", function(x) {
return x;
})
// 例3 返回选项
var select = `<select name="" id="" multiple="multiple" size="2">
<option value="HTML" selected="selected">HTML</option>
<option value="CSS" selected="selected">CSS</option>
<option value="JS">JS</option>
<option value="Vue">Vue</option>
</select>`;
document.write(select);
var elems = document.querySelectorAll('select option:checked');
var values = Array.prototype.map.call(elems, function(obj) {
return obj.value;
})
console.log(values); // ["HTML", "CSS"]
some()
// some() 方法测试数组中的某些元素是否通过由提供的函数实现的测试
var arr2 = ['Prosper', 'Lee', 'is', ['very', 'very'], 'nice', '!', , null];
arr2.some(function (currentValue, index, array) {
return currentValue == 'is'; // 通过true
})
every()
// every() 方法测试数组的所有元素是否都通过了指定函数的测试
var arr2 = ['Prosper', 'Lee', 'is', ['very', 'very'], 'nice', '!', , null];
arr2.every(function (currentValue, index, array) {
return currentValue == 'Prosper'; // 不通过false
})
var arr3 = ['Prosper','Prosper','Prosper','Prosper','Prosper','Prosper'];
arr3.every(function (currentValue, index, array) {
return currentValue == 'Prosper'; // 通过true
})
filter()
// filter() 方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素
var arr4 = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
var result = arr4.filter(word => word.length > 6);
console.log(result);
indexOf()
// indexOf() str.indexOf(searchValue[, fromIndex]) 方法返回调用 String对象中第一次出现的指定值的索引,开始在 fromIndex进行搜索。如果未找到该值,则返回-1。
var arr5 = ['Prosper', 'Lee', 'is', 'very', 'nice', '!!!'];
console.log(arr5.indexOf("Pro", 0)); // returns -1
console.log(arr5.indexOf("Pro")); // returns -1
console.log(arr5.indexOf("Lee")); // returns 1
console.log(arr5.indexOf("Lee",2)); // returns -1
console.log("Prosper Lee".indexOf("Prosper")); // returns 0
console.log("Prosper Lee".indexOf("Lee")); // returns 8
console.log("Prosper Lee".indexOf("Prosper", 0)); // returns 0
console.log("Prosper Lee".indexOf("Prosper", 5)); // returns -1
console.log("Prosper Lee".indexOf("z")); // returns -1
console.log("Prosper Lee".indexOf("", 10)); // returns 10
console.log("Prosper Lee".indexOf("", 11)); // returns 11
console.log("Prosper Lee".indexOf("", 12)); // returns 11
// lastIndexOf() 方法可返回一个指定的字符串值最后出现的位置。第二个参数为从0开始查,查到第几个结束
console.log('Prosper Lee'.lastIndexOf('e')); //
console.log('Prosper Lee'.lastIndexOf('o')); //
console.log('Prosper Lee'.lastIndexOf('b')); // -1
console.log('Prosper Lee'.lastIndexOf('e',4)); // -1
console.log('Prosper Lee'.lastIndexOf('e',5)); //
console.log('Prosper Lee'.lastIndexOf('e',9)); //
console.log('Prosper Lee'.lastIndexOf('e',10)); //
// array.reduce(function (accumulator, currentValue, currentIndex, array) {}, initialValue)
[{x: 1}, {x:2}, {x:3}].reduce((accumulator, currentValue) => accumulator + currentValue.x, 0); //
[[0, 1], [2, 3], [4, 5]].reduce(( acc, cur ) => acc.concat(cur), []); // [0,1,2,3,4,5]
// 统计出现次数
['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'].reduce(function (allNames, name) {
allNames[name] = ++allNames[name] || 1;
// if (name in allNames) {
// allNames[name]++;
// } else {
// allNames[name] = 1;
// }
return allNames;
}, {}); // { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }
// 按属性对object分类节
var people = [{
name: 'Alice',
age: 21
},
{
name: 'Max',
age: 20
},
{
name: 'Jane',
age: 20
}
];
function groupBy(objectArray, property) {
return objectArray.reduce(function (acc, obj) {
var key = obj[property];
// console.log(key); // 21 20 20
if (!acc[key]) { // undefined时才定义空数组
acc[key] = [];
}
acc[key].push(obj);
return acc;
}, {});
}
console.log(groupBy(people, 'age'));
// groupedPeople is:
// {
// 20: [
// { name: 'Max', age: 20 },
// { name: 'Jane', age: 20 }
// ],
// 21: [{ name: 'Alice', age: 21 }]
// }
[0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => { return accumulator + currentValue; }, 10 ); //
// callback accumulator currentValue currentIndex array return value
// [1 call] 10 0 0 [0, 1, 2, 3, 4] 10
// [2 call] 10 1 1 [0, 1, 2, 3, 4] 11
// [3 call] 11 2 2 [0, 1, 2, 3, 4] 13
// [4 call] 13 3 3 [0, 1, 2, 3, 4] 16
// [5 call] 16 4 4 [0, 1, 2, 3, 4] 20
reduceRight()
// array.reduceRight(function (previousValue, currentValue, index, array) {}, initialValue)
[0, 1, 2, 3, 4].reduceRight((previousValue, currentValue, index, array) => { return previousValue + currentValue; }, 10); //
// callback accumulator currentValue currentIndex array return value
// [1 call] 10 4 4 [0, 1, 2, 3, 4] 14
// [2 call] 14 3 3 [0, 1, 2, 3, 4] 17
// [3 call] 17 2 2 [0, 1, 2, 3, 4] 19
// [4 call] 19 1 1 [0, 1, 2, 3, 4] 20
// [5 call] 20 0 0 [0, 1, 2, 3, 4] 20
['1', '2', '3', '4', '5'].reduce((prev, cur) => prev + cur); //
['1', '2', '3', '4', '5'].reduceRight((prev, cur) => prev + cur); //
// Array.isArray() 用于确定传递的值是否是一个 Array。
Array.isArray([1, 2, 3]); // true
Array.isArray({foo: 123}); // false
Array.isArray("foobar"); // false
Array.isArray(undefined); // false
Array.from()
// Array.from() 方法从一个类似数组或可迭代对象中创建一个新的数组实例。
Array.from(['a', 'b', 'c'], (v, i) => i + "->" + v ); // ["0->a", "1->b", "2->c"]
Array.from(['a', 'b', 'c'], x => x + x ); // ["aa", "bb", "cc"]
Array.from({ length: 5 }, (v, i) => i); // [0, 1, 2, 3, 4]
var m = [1, 2, 2], n = [2,3,3];
function combine(){
let arr = [].concat.apply([], arguments); // 没有去重的新数组
console.log(arr);
return Array.from(new Set(arr));
}
console.log(combine(m,n));
trim()
// trim() 去掉字符串前后空白
console.log(' Prosper Lee '.trim()); // "Prosper Lee"
console.log('Prosper Lee '.replace(/^\s+|\s+$/g, "z")); // "Prosper Leez" // 兼容: 将前后有空格的位置替换成z
ES5新增的更多相关文章
- 4日6日--ES5新增数组方法
forEach使用的函数调用,所以占内存比较大,不如定长for循环和迭代for循环 1.通过forEach将数组中的元素逐个表示出来(遍历方法,读取操作). 2.通过map将原数组中的元素进行算数运算 ...
- String方法,js中Array方法,ES5新增Array方法,以及jQuery中Array方法
相关阅读:https://blog.csdn.net/u013185654/article/details/78498393 相关阅读:https://www.cnblogs.com/huangyin ...
- js数组定义和方法 (包含ES5新增数组方法)
数组Array 1. 数组定义 一系列数据的集合成为数组.数组的元素可以为任何类型的数据(包括数组,函数等),每个元素之间用逗号隔开,数组格式:[1,2,3]. 2. 数组创建方式 (1) 字面量方法 ...
- ES5新增数组方法测试和字符串常见API测试
首先是ES5新增数组方法测试: <!DOCTYPE html><html lang="en"><head> <meta charset=& ...
- ES5新增的数组方法
ES5新增:(IE9级以上支持)1.forEach():遍历数组,无返回值,不改变原数组.2.map():遍历数组,返回一个新数组,不改变原数组.3.filter():过滤掉数组中不满足条件的值,返回 ...
- 学习笔记-es5新增的一些数组的API(不全)-字符串-字符串API(不全)
### es5新增的数组的api + indexOf() 搜索数组中的元素,并返回它所在的位置. arr.indexOf(str,index) 参数: str为要查找的字符串 index为开始查找的下 ...
- ES5新增数组的方法
ES5新增数组的方法 ES5新增数组常见方法(indexOf/forEach/map/filter/some/every) .indexOf( data , start) 检测数组中是否存在指定数据 ...
- ES5新增数组方法every()、some()、filter()、map()
JavaScript ES5标准中新增了一些Array方法,如every().some().filter().map().它们的出现使我们能够更加便利地操作数组,但对IE9以下浏览器的兼容性比较差.下 ...
- this与bind(this) (es5新增)
this与bind(this) this this指向的是当前函数的作用域(对象实例),有如下的例子 const app = { name: 'xiaoming', log() { console.l ...
- 复习——高级语法对象原型,es5新增语法
今天的开始进入了js的高级语法 我马上也要复习完了,之前学到闭包递归,就回去复习去了,复都复习这么久而且,复习的过程真的比学知识的过程难熬的多,只不过终于要复习完了,再来点es6的新语法马上就要步入v ...
随机推荐
- Java作业五(2017-10-15)
/*3-6.程序员;龚猛*/ 1 package zhenshu; import java.util.Scanner; public class text { public static void m ...
- DCOS实践分享(3):基于Mesos 和 Docker企业级移动应用实践分享
2016年1月24日 8:00—19:00 北京万豪酒店(东城区建国门南大街7号) @Container大会是由国内容器社区DockOne组织的专为一线开发者和运维工程师设计的顶级容器技术会议,会议强 ...
- Egg 中 Controller 最佳实践
得益于 JavaScript 加入的 decorator 特性,可以使我们跟 Java/C# 一样,更加直观自然的,做面向切面编程.而随着 TypeScript 的成熟,类型系统也让我们增强了信心,面 ...
- 字符串匹配(二)----KMP算法
什么是KMP算法: KMP算法是一种改进的字符串匹配算法,由D.E.Knuth,J.H.Morris和V.R.Pratt同时发现,因此人们称它为克努特——莫里斯——普拉特操作(简称KMP算法).KMP ...
- [Swift]LeetCode963. 最小面积矩形 II | Minimum Area Rectangle II
Given a set of points in the xy-plane, determine the minimum area of any rectangle formed from these ...
- [Abp 源码分析]二、模块系统
0.简介 整个 Abp 框架由各个模块组成,基本上可以看做一个程序集一个模块,不排除一个程序集有多个模块的可能性.可以看看他官方的这些扩展库: 可以看到每个项目文件下面都会有一个 xxxModule ...
- python获取当前运行程序的名字
import os filename = os.path.abspath(__file__) print filename 打印结果: E:\bluedon\test.py
- BBS论坛(一)
1.1.项目结构搭建 (1)创建flask项目Perfect_bbs,然后搭建项目结构如下: (2)构建蓝图 cms/views.py # cmd/views.py from flask import ...
- C++版 - HDUoj 2010 3阶的水仙花数 - 牛客网
版权声明: 本文为博主Bravo Yeung(知乎UserName同名)的原创文章,欲转载请先私信获博主允许,转载时请附上网址 http://blog.csdn.net/lzuacm. C++版 - ...
- Chorme浏览器渲染MathJax时出现竖线的解决方法
Chorme浏览器渲染MathJax时出现竖线的原因分析与解决方法 查资料知,Chorme中显示MathJax时出现竖线的原因如下: 新版的Chorme浏览器在解析css时,会对其中的值进行向上取整( ...