当前位置:网站首页>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
边栏推荐
- [2021] Spatio-Temporal Graph Contrastive Learning
- Live delivery form template - automatically display pictures - automatically associate series products
- MySQL foreign key constraint
- leetcode——启发式搜索
- C. Tree infection (simulation + greed)
- Redis data type usage scenario
- The applet calls the function of scanning QR code and jumps to the path specified by QR code
- The 8 diagrams let you see the execution sequence of async / await and promise step by step
- Basic theory of Flink
- Logrus set log format and output function name
猜你喜欢
MySQL - index
跨境电商 | Facebook 和 Instagram:哪个社交媒体更适合你?
使用zerotier让异地设备组局域网
2022/4/22
好的测试数据管理,到底要怎么做?
Transaction isolation level of MySQL transactions
[winui3] Écrivez une copie du gestionnaire de fichiers Explorer
Where, on when MySQL external connection is used
Flip coin (Blue Bridge Cup)
Deep learning notes - semantic segmentation and data sets
随机推荐
Day.js 常用方法
Other problems encountered in debugging fingerprints
What are instruction cycles, machine cycles, and clock cycles?
Unique primary key ID of tidb sub table -- solution to failure of sequence and Gorm to obtain primary key
TypeError: ‘Collection‘ object is not callable. If you meant to call the ......
[WinUI3]編寫一個仿Explorer文件管理器
On distributed lock
Live delivery form template - automatically display pictures - automatically associate series products
mysql5. 7. X data authorization leads to 1141
Download PDF from HowNet (I don't want to use CAJViewer anymore!!!)
Independent station operation | Facebook marketing artifact - chat robot manychat
Machine learning - linear regression
C. Tree infection (simulation + greed)
DevOps生命周期,你想知道的全都在这里了!
COM in wine (2) -- basic code analysis
Interview summary
View, modify and delete [database] table
In aggregated query without group by, expression 1 of select list contains nonaggregated column
The applet calls the function of scanning QR code and jumps to the path specified by QR code
[database] MySQL multi table query (I)