##entries(), keys(), values() |
|
Modify the original array
- push() adds one or more elements to the end of the array and returns the new length.
- unshift() adds one or more elements to the beginning of the array and returns the new length.
- pop() Removes and returns the last element of the array
- shift() Removes and returns the first element of the array
- sort() Sorts the elements of the array
- reverse() Reverse the order of elements in the array.
- splice() removes elements and adds new elements to the array.
splice
Syntax
arrayObject.splice(index,howmany,item1,...,itemX)
var arr = new Array();
arr[0] = "George";
arr[1] = "John";
arr[2] = "Thomas";
arr.splice(2,1); //"George", "John"
arr.splice(1,0,"William"); //"George", "William", "John"
arr.splice(2,1,"haha"); //"George", "William", "haha"
Does not modify the original array
- concat() concatenates two or more arrays and returns the result.
- join() puts all elements of the array into a string. Elements are separated by the specified delimiter.
- slice() Returns selected elements from an existing array
slice
Syntax
arrayObject.slice(start,end);
- start Required. Specifies where to start the selection. Can be negative, counting from the end of the array.
- end Optional. Specifies where the selection ends. If not specified, the sliced array contains all elements from start to the end of the array. Can be negative, counting from the end of the array.
var arr = new Array();
arr[0] = "George";
arr[1] = "John";
arr[2] = "Thomas";
arr.slice(2,1); //[]
arr.slice(1,2); //"William"
arr.slice(-2,-1); //"William"
Convert array-like objects (such as arguments) into real arrays
Array.prototype.slice.call(arguments);
ES5 new Array
- Index method: indexOf(), lastIndexOf()
- Iteration method: forEach(), map(), filter(), some(), every( )
- Merge method: reduce(), reduceRight()
The method will not modify the original array
Index method
indexOf
array.indexOf(searchElement[, fromIndex])
- Returns the integer index value, if there is no match (strict match), returns -1.
- fromIndex is optional, indicating that the search starts from this position. If the default or the format does not meet the requirements, use the default value 0.
var data = [2, 5, 7, 3, 5];
console.log(data.indexOf(5, "x")); // 1 ("x"被忽略)
console.log(data.indexOf(5, "3")); // 4 (从3号位开始搜索)
lastIndexOf
array.lastIndexOf(searchElement[, fromIndex])
- Search from the end of the string, not from the beginning.
- The default value of fromIndex is array.length - 1.
var data = [2, 5, 7, 3, 5];
console.log(data.lastIndexOf(5)); // 4
console.log(data.lastIndexOf(5, 3)); // 1 (从后往前,索引值小于3的开始搜索)
console.log(data.lastIndexOf(4)); // -1 (未找到)
The two methods will use the equality operator when comparing the first parameter with each item in the array. They must be completely equal, otherwise -1 will be returned.
Iteration method
Each method accepts two parameters, the first parameter callback (callback function, required), the second parameter The first parameter is an optional context parameter.
- The first parameter callback accepts three parameters, the value of the current item, the index of the current item in the array, and the array object itself. That is, function(value,index,arr) {}; it should be noted that the difference from the method encapsulated in our commonly used jQuery is the first parameter and the second parameter, that is, the order of index and value is reversed.
- The second parameter is an optional context parameter, which is the scope object that executes the first function parameter, which is the value pointed to by this in the callback mentioned above. If the second optional parameter is not specified, the global object is used instead (window in browsers), or even undefined in strict mode.
It should be noted that except for the forEach() method, the callback in the other iteration methods needs to have a return value, otherwise undefined will be returned.
forEach
forEach() loops through the array and runs the given function on each item in the array. This method has no return value.
[].forEach(function(value, index, array) {
// ...
}, [ thisObject]);
- In addition to accepting a required callback function parameter, forEach can also accept an optional context parameter (changing the this pointer in the callback function) (the second parameter).
- If the second optional parameter is not specified, the global object will be used instead (window in the browser), or even undefined in strict mode.
[1, 2, 3, 4].forEach(function (item, index, array) {
console.log(array[index] == item); // true
sum += item;
});
alert(sum); // 10
var database = {
users: ["张含韵", "江一燕", "李小璐"],
sendEmail: function (user) {
if (this.isValidUser(user)) {
console.log("你好," + user);
} else {
console.log("抱歉,"+ user +",你不是本家人");
}
},
isValidUser: function (user) {
return /^张/.test(user);
}
};
// 给每个人法邮件
database.users.forEach( // database.users中人遍历
database.sendEmail, // 发送邮件
database // 使用database代替上面标红的this
);
// 结果:
// 你好,张含韵
// 抱歉,江一燕,你不是本家人
// 抱歉,李小璐,你不是本家
map
map() refers to "mapping", which runs a given function on each item in the array and returns an array composed of the results of each function call.
[].map(function(value, index, array) {
// ...
}, [ thisObject]);
var data = [1, 2, 3, 4];
var arrayOfSquares = data.map(function (item) {
return item * item;
});
alert(arrayOfSquares); // 1, 4, 9, 16
filter
filter(), "filter", runs the given function on each item in the array and returns an array that meets the filter conditions.
array.filter(callback,[ thisObject]);
- Filter’s callback function needs to return a Boolean value of true or false.
- As long as the return value is weakly equal to == true/false, it does not have to return === true/false.
var arr3 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var flag = arr3.filter(function(value, index) {
return value % 3 === 0;
});
console.log(flag); // [3, 6, 9]
every
every(), determines whether each item in the array meets the given conditions. When all items meet the conditions, it will return true.
Note: If the array is empty, true will be returned
array.every(callback,[ thisObject]);
var arr4 = [1, 2, 3, 4, 5];
var flag = arr4.every(function(value, index) {
return value % 2 === 0;
});
console.log(flag); // false
some
#some() determines whether there are items in the array that meet the conditions. As long as one item meets the conditions, it will return true.
Note: If the array is empty, false will be returned
array.some(callback,[ thisObject]);
var arr5 = [1, 2, 3, 4, 5];
var flag = arr5.some(function(value, index) {
return value % 2 === 0;
});
console.log(flag); // true
Merge method
这两个方法相比前面可能稍微复杂一些,它们都会迭代数组中的所有项,然后生成一个最终返回值。这两个方法接收两个参数。
- 第一个参数callback,函数接受4个参数分别是(初始值total必选,当前值currentValue必选,索引值currentIndex可选,当前数组arr可选),函数需要返回一个值,这个值会在下一次迭代中作为初始值。
- 第二个参数是迭代初始值(initialValue),参数可选,如果缺省,初始值为数组第一项,从数组第一个项开始叠加,缺省参数要比正常传值少一次运算。
reduce
reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。 reduce() 对于空数组是不会执行回调函数的。
array. reduce(function(total, currentValue, currentIndex, array) {<br> // ...<br>});
var arr9 = [1, 2, 3, 4];
var sum9 =arr9.reduce(function (total, curr, index, array) {
return total * curr;
});
console.log(sum9); // 24
var sum9_1 =arr9.reduce(function (total, curr, index, array) {
return total * curr;
}, 10);
console.log(sum9_1); // 240
reduceRight
reduceRight()和reduce()相比,用法类似,差异在于reduceRight是从数组的末尾开始实现的。
array.reduceRight(callback,[ thisObject]);
var arr9 = [2, 45, 30, 80];
var flag = arr9.reduceRight(function (total, curr, index) {
return total - curr;
});
var flag_1 = arr9.reduceRight(function (total, curr, index) {
return total - curr;
},200);
console.log(flag); // 3
console.log(flag_1); // 43
Array方法
isArray
判断参数是否是”Array”返回true或false。
var a = [1,2,3];
Array.isArray(a); //true
ES6数组方法
Array方法
Array.from()
用于将两类对象转为真正的数组:类似数组的对象(array-like object)和可遍历(iterable)的对象(包括 ES6 新增的数据结构 Set 和 Map)。
let arrayLike = {
'0': 'a',
'1': 'b',
'2': 'c',
length: 3
};
let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']
Array.from还可以接受第二个参数,作用类似于数组的map方法,用来对每个元素进行处理,将处理后的值放入返回的数组。
Array.from(arrayLike, x => x * x);
// 等同于
Array.from(arrayLike).map(x => x * x);
Array.from([1, 2, 3], (x) => x * x)
// [1, 4, 9]
Array.of()
用于将一组值,转换为数组。
Array.of(3, 11, 8) // [3,11,8]
Array.of(3) // [3]
实例方法
会改变原数组
在当前数组内部,将指定位置的成员复制到其他位置(会覆盖原有成员),然后返回当前数组。
array. copyWithin(target, start = 0, end = this.length);
- target(必需):从该位置开始替换数据。如果为负值,表示倒数。
- start(可选):从该位置开始读取数据,默认为 0。如果为负值,表示倒数。
- end(可选):到该位置前停止读取数据,默认等于数组长度。如果为负值,表示倒数。
// 将3号位复制到0号位
[1, 2, 3, 4, 5].copyWithin(0, 3, 4)
// [4, 2, 3, 4, 5]
// -2相当于3号位,-1相当于4号位
[1, 2, 3, 4, 5].copyWithin(0, -2, -1)
// [4, 2, 3, 4, 5]
使用给定值,填充一个数组。
['a', 'b', 'c'].fill(7); // [7, 7, 7]
let arr = new Array(3).fill([]);
arr[0].push(5); // [[5], [5], [5]]
不会改变原数组
用于找出第一个符合条件的数组成员。它的参数是一个回调函数,所有数组成员依次执行该回调函数,直到找出第一个返回值为true的成员,然后返回该成员。如果没有符合条件的成员,则返回undefined。
find方法的回调函数可以接受三个参数,依次为当前的值、当前的位置和原数组。
[1, 4, -5, 10].find((n) => n < 0)
// -5
[1, 5, 10, 15].find(function(value, index, arr) {
return value > 9;
}) // 10
findIndex方法的用法与find方法非常类似,返回第一个符合条件的数组成员的位置,如果所有成员都不符合条件,则返回-1。
[1, 5, 10, 15].findIndex(function(value, index, arr) {
return value > 9;
}) // 2
返回一个布尔值,表示某个数组是否包含给定的值。
[1, 2, 3].includes(2) // true
ES6提供了三个新方法:entries()、keys()和values(),用来遍历数组。它们都返回一个遍历器对象,可以用for...of循环进行遍历,唯一的区别是keys()是对数组的键名的遍历、values()是对数组键值的遍历,entries()方法是对数值的键值对的遍历。
for (let index of ['a', 'b'].keys()) {
console.log(index);
}
// 0
// 1
for (let elem of ['a', 'b'].values()) {
console.log(elem);
}
// 'a'
// 'b'
for (let [index, elem] of ['a', 'b'].entries()) {
console.log(index, elem);
}
// 0 "a"
// 1 "b"
如果不使用for...of循环,可以手动调用遍历器对象的next方法,进行遍历。
let letter = ['a', 'b', 'c'];
let entries = letter.entries();
console.log(entries.next().value); // [0, 'a']
console.log(entries.next().value); // [1, 'b']
console.log(entries.next().value); // [2, 'c']
【推荐学习:javascript高级教程】