Array 对象方法
| 方法 | 描述 |
|---|---|
| concat() | 连接两个或更多的数组,并返回结果。 |
| join() | 把数组的所有元素放入一个字符串。元素通过指定的分隔符进行分隔。 |
| pop() | 删除并返回数组的最后一个元素 |
| push() | 向数组的末尾添加一个或更多元素,并返回新的长度。 |
| reverse() | 颠倒数组中元素的顺序。 |
| reduce() | 接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。 |
| shift() | 删除并返回数组的第一个元素 |
| slice() | 从某个已有的数组返回选定的元素 |
| sort() | 对数组的元素进行排序 |
| splice() | 删除元素,并向数组添加新元素。 |
| toSource() | 返回该对象的源代码。 |
| toString() | 把数组转换为字符串,并返回结果。 |
| toLocaleString() | 把数组转换为本地数组,并返回结果。 |
| unshift() | 向数组的开头添加一个或更多元素,并返回新的长度。 |
| valueOf() | 返回数组对象的原始值 |
如 unshift() 方法
语法
arrayObject.unshift(newelement1,newelement2,....,newelementX)
| 参数 | 描述 |
|---|---|
| newelement1 | 必需。向数组添加的第一个元素。 |
| newelement2 | 可选。向数组添加的第二个元素。 |
| newelement3 | 可选。可添加若干个元素。 |
如 reduce() 方法
语法
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
| 参数 | 描述 |
|---|---|
| total | 必需。初始值, 或者计算结束后的返回值。 |
| currentValue | 必需。当前元素。 |
| currentIndex | 可选。当前元素的索引。 |
| arr | 可选。当前元素所属的数组对象。 |
示例:
var numbers = [15.5, 2.3, 1.1, 4.7];
function getSum(total, num) {
return total + Math.round(num);
}
console.log("四舍五入后计算数组元素的总和:",numbers.reduce(getSum, 0));