当前位置:网站首页>JS Array常见方法
JS Array常见方法
2022-04-23 05:10:00 【sereposika】
Array.entries()
entries()
方法返回一个新的Array Iterator对象,该对象包含数组中每个索引的键/值对。
生成可迭代对象,使用next()方法进行遍历,用,done属性作为循环条件
const array1 = ['a', 'b', 'c'];
const iterator1 = array1.entries();
console.log(iterator1.next().value);
// expected output: Array [0, "a"]
console.log(iterator1.next().value);
// expected output: Array [1, "b"]
var arr = ["a", "b", "c"];
var iterator = arr.entries();
// undefined
for (let e of iterator) {
console.log(e);
}
// [0, "a"]
// [1, "b"]
// [2, "c"]
//二维数组的遍历
function sortArr(arr) {
var goNext = true;
var entries = arr.entries();
while (goNext) {
var result = entries.next();
if (result.done !== true) {
result.value[1].sort((a, b) => a - b);
goNext = true;
} else {
goNext = false;
}
}
return arr;
}
var arr = [[1,34],[456,2,3,44,234],[4567,1,4,5,6],[34,78,23,1]];
sortArr(arr);
/*(4) [Array(2), Array(5), Array(5), Array(4)]
0:(2) [1, 34]
1:(5) [2, 3, 44, 234, 456]
2:(5) [1, 4, 5, 6, 4567]
3:(4) [1, 23, 34, 78]
length:4
__proto__:Array(0)
*/
Array.prototype.filter()
filter()
方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。
过滤数组,将满足条件的值传入一个新数组中。
过滤掉数组中的无效数据
var arr = [
{ id: 15 },
{ id: -1 },
{ id: 0 },
{ id: 3 },
{ id: 12.2 },
{ },
{ id: null },
{ id: NaN },
{ id: 'undefined' }
];
var invalidEntries = 0;
function isNumber(obj) {
return obj !== undefined && typeof(obj) === 'number' && !isNaN(obj);
}
function filterByID(item) {
if (isNumber(item.id) && item.id !== 0) {
return true;
}
invalidEntries++;
return false;
}
var arrByID = arr.filter(filterByID);
console.log('Filtered Array\n', arrByID);
// Filtered Array
// [{ id: 15 }, { id: -1 }, { id: 3 }, { id: 12.2 }]
Array.from()
Array.from()
方法对一个类似数组或可迭代对象创建一个新的,浅拷贝的数组实例
**Array.from()**
方法对一个类似数组或可迭代对象创建一个新的,浅拷贝的数组实例。
Array.from()
可以通过以下方式来创建数组对象:
-
伪数组对象(拥有一个
length
属性和若干索引属性的任意对象) -
可迭代对象(可以获取对象中的元素,如 Map和 Set 等)
//将set转化为 数组
const set = new Set(['foo', 'bar', 'baz', 'foo']);
Array.from(set);
// [ "foo", "bar", "baz" ]
//将map转化为数组结构
const map = new Map([[1, 2], [2, 4], [4, 8]]);
Array.from(map);
// [[1, 2], [2, 4], [4, 8]]
const mapper = new Map([['1', 'a'], ['2', 'b']]);
Array.from(mapper.values());
// ['a', 'b'];
Array.from(mapper.keys());
// ['1', '2'];
//处理出入的arguments
function f() {
return Array.from(arguments);
}
f(1, 2, 3);
// [ 1, 2, 3 ]
序列生成
const range = (start, stop, step) => Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step));
// Generate numbers range 0..4
range(0, 4, 1);
// [0, 1, 2, 3, 4]
// Generate numbers range 1..10 with step of 2
range(1, 10, 2);
// [1, 3, 5, 7, 9]
Array.join()
join()
方法将一个数组(或一个类数组对象)的所有元素连接成一个字符串并返回这个字符串。如果数组只有一个项目,那么将返回该项目而不使用分隔符。
const elements = ['Fire', 'Air', 'Water'];
console.log(elements.join());
// expected output: "Fire,Air,Water"
console.log(elements.join(''));
// expected output: "FireAirWater"
console.log(elements.join('-'));
// expected output: "Fire-Air-Water"
Array.map()
map()
方法创建一个新数组,这个新数组由原数组中的每个元素都调用一次提供的函数后的返回值组成。
var kvArray = [{key: 1, value: 10},
{key: 2, value: 20},
{key: 3, value: 30}];
var reformattedArray = kvArray.map(function(obj) {
var rObj = {};
rObj[obj.key] = obj.value;
return rObj;
});
Array.prototype.slice()
slice()
方法返回一个新的数组对象,这一对象是一个由 begin
和 end
决定的原数组的浅拷贝(包括 begin
,不包括end
)。原始数组不会被改变。
var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
var citrus = fruits.slice(1, 3);
// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
// citrus contains ['Orange','Lemon']
Array.prototype.flat()
flat()
方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。
扁平化嵌套数组
var arr1 = [1, 2, [3, 4]];
arr1.flat();
// [1, 2, 3, 4]
var arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]
var arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]
//使用 Infinity,可展开任意深度的嵌套数组
var arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// 使用 reduce、concat 和递归展开无限多层嵌套的数组
var arr1 = [1,2,3,[1,2,3,4, [2,3,4]]];
function flatDeep(arr, d = 1) {
return d > 0 ? arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatDeep(val, d - 1) : val), [])
: arr.slice();
};
flatDeep(arr1, Infinity);
// [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]
使用堆栈stack
// 无递归数组扁平化,使用堆栈
// 注意:深度的控制比较低效,因为需要检查每一个值的深度
// 也可能在 shift / unshift 上进行 w/o 反转,但是末端的数组 OPs 更快
var arr1 = [1,2,3,[1,2,3,4, [2,3,4]]];
function flatten(input) {
const stack = [...input];
const res = [];
while (stack.length) {
// 使用 pop 从 stack 中取出并移除值
const next = stack.pop();
if (Array.isArray(next)) {
// 使用 push 送回内层数组中的元素,不会改动原始输入
stack.push(...next);
} else {
res.push(next);
}
}
// 反转恢复原数组的顺序
return res.reverse();
}
flatten(arr1);// [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]
版权声明
本文为[sereposika]所创,转载请带上原文链接,感谢
https://blog.csdn.net/m0_51737221/article/details/124094844
边栏推荐
- The vscode ipynb file does not have code highlighting and code completion solutions
- 跨境电商 | Facebook 和 Instagram:哪个社交媒体更适合你?
- Unity C# 网络学习(四)
- 数据安全问题已成隐患,看vivo如何让“用户数据”重新披甲
- QPushbutton 槽函数被多次触发
- MySQL memo (for your own query)
- Summary of MySQL knowledge points
- Get the number of days between dates, get the Chinese date, get the date of the next Monday of the date, get the working day, get the rest day
- Deep learning notes - object detection and dataset + anchor box
- C language hash dictionary and notes
猜你喜欢
[2021] Spatio-Temporal Graph Contrastive Learning
Jupyter notebook crawling web pages
Deep learning notes - object detection and dataset + anchor box
[2021] Spatio-Temporal Graph Contrastive Learning
7-4 is it too fat (10 points) PTA
跨境电商 | Facebook 和 Instagram:哪个社交媒体更适合你?
好的测试数据管理,到底要怎么做?
持续集成(CI)/持续交付(CD)如何彻底改变自动化测试
Summary of MySQL knowledge points
源码剖析Redis中如何使用跳表的
随机推荐
Jupyter notebook crawling web pages
This call when the transaction does not take effect
Basic theory of Flink
How can continuous integration (CI) / continuous delivery (CD) revolutionize automated testing
2022/4/22
How to exit VIM
mysql5. 7. X data authorization leads to 1141
Leetcode -- heuristic search
JS engine loop mechanism: synchronous, asynchronous, event loop
The WebService interface writes and publishes calls to the WebService interface (I)
Set Chrome browser background to eye protection (eye escort / darkreader plug-in)
机器学习---线性回归
The 8 diagrams let you see the execution sequence of async / await and promise step by step
Some experience in using MySQL / tidb database [slowly updating...]
Summary of R & D technology
Download PDF from HowNet (I don't want to use CAJViewer anymore!!!)
深度学习笔记 —— 物体检测和数据集 + 锚框
API slow interface analysis
At pgconf Asia Chinese technology forum, listen to Tencent cloud experts' in-depth understanding of database technology
Introduction to load balancing