Advanced JavaScript Array Methods: fill and reverse
2016-06-16 16:45
507 查看
In addition to the basic methods forJavaScript arrays there are some new, powerful techniques for modifying array content. Like push,
pop, shift and unshift , these methods are referred to as mutators , due to the fact that they modify the array. In this article, I’ll cover two:
“Zeroes out” an array with any replacement value. Given an array of
“Wiping out” every record in the array and viewing the result in the console:
the point from which the fill will take place. Taking the current state of
with:
The result:
where the fill stops . Of course, the fill “insert” value can be anything you wish: a number, string, or
for example.
Opera; Mozilla Developer Network suggests a polyfill for those and older browser versions.
Pretty straightforward:
Reversing the array and showing the results in the console:
pop, shift and unshift , these methods are referred to as mutators , due to the fact that they modify the array. In this article, I’ll cover two:
filland
reverse.
fill
“Zeroes out” an array with any replacement value. Given an array of scores:
var scores = [15, 22, 3, 7, 11];
“Wiping out” every record in the array and viewing the result in the console:
scores.fill(0); > [0, 0, 0, 0, 0]
fillcan take two other arguments: the first,
startis
the point from which the fill will take place. Taking the current state of
scores, we can fill from the third value
with:
scores.fill(4,2);
The result:
> [0, 0, 4, 4, 4]
fillcan also take an
endvalue,
where the fill stops . Of course, the fill “insert” value can be anything you wish: a number, string, or
null,
for example.
fillis part of ES6 / JS 2015, and is therefore supported in all recent browser versions except for IE and
Opera; Mozilla Developer Network suggests a polyfill for those and older browser versions.
reverse
Pretty straightforward: reversereverses the order of elements. Given an array
molluscs:
var molluscs = ["oysters", "mussels", "limpets"];
Reversing the array and showing the results in the console:
molluscs.reverse() > ["limpets", "mussels", "oysters"]
相关文章推荐
- JQuery1——基础($对象,选择器,对象转换)
- Android学习笔记(二九):嵌入浏览器
- Android java 与 javascript互访(相互调用)的方法例子
- JavaScript演示排序算法
- javascript实现10进制转为N进制数
- 最后一次说说闭包
- Ajax
- 2019年开发人员应该学习的8个JavaScript框架
- HTML中的script标签研究
- 对一个分号引发的错误研究
- 异步流程控制:7 行代码学会 co 模块
- ES6 走马观花(ECMAScript2015 新特性)
- JavaScript拆分字符串时产生空字符的原因
- Canvas 在高清屏下绘制图片变模糊的解决方法
- Redux系列02:一个炒鸡简单的react+redux例子
- JavaScript 各种遍历方式详解
- call/apply/bind 的理解与实例分享