use*_*od2 83 javascript arrays
我有2个数组:
var a = [1, 2, 3]
var b = [a, b, c]
Run Code Online (Sandbox Code Playgroud)
我想得到的结果是:
[[1, a], [2, b], [3, c]]
Run Code Online (Sandbox Code Playgroud)
这看起来很简单,但我无法弄清楚.
我希望结果是一个数组,两个数组中的每个元素都压缩在一起.
tew*_*hia 161
使用map方法:
var a = [1, 2, 3]
var b = ['a', 'b', 'c']
var c = a.map(function(e, i) {
return [e, b[i]];
});
console.log(c)Run Code Online (Sandbox Code Playgroud)
Rok*_*jan 14
Array.prototype.map() 旧版浏览器不支持
const a = [1, 2, 3],
b = ['a', 'b', 'c'];
const zip = (arr1, arr2) => arr1.map((k, i) => [k, arr2[i]]);
console.log(zip(a, b)) // [[1, "a"], [2, "b"], [3, "c"]]Run Code Online (Sandbox Code Playgroud)
这是一个适用于所有地方的替代方案
var a = [1, 2, 3],
b = ['a', 'b', 'c'];
var zip = [];
for (var i = 0; i < a.length; i++){
zip.push([a[i], b[i]]);
}
console.log(zip); // [[1, "a"], [2, "b"], [3, "c"]]Run Code Online (Sandbox Code Playgroud)
您还可以使用生成器函数来zip().
const a = [1, 2, 3]
const b = ['a', 'b', 'c']
/**
* Zips any number of arrays. It will always zip() the largest array returning undefined for shorter arrays.
* @param {...Array<any>} arrays
*/
function* zip(...arrays){
const maxLength = arrays.reduce((max, curIterable) => curIterable.length > max ? curIterable.length: max, 0);
for (let i = 0; i < maxLength; i++) {
yield arrays.map(array => array[i]);
}
}
// put zipped result in an array
const result = [...zip(a, b)]
// or lazy generate the values
for (const [valA, valB] of zip(a, b)) {
console.log(`${valA}: ${valB}`);
}Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }Run Code Online (Sandbox Code Playgroud)
上面的方法适用于任意数量的数组,并且zip()最长的数组undefined将作为较短数组的值返回。
Iterables这里的函数可用于所有Iterables(例如Maps,Sets或您的自定义Iterable),而不仅仅是数组。
const a = [1, 2, 3];
const b = ["a", "b", "c"];
/**
* Zips any number of iterables. It will always zip() the largest Iterable returning undefined for shorter arrays.
* @param {...Iterable<any>} iterables
*/
function* zip(...iterables) {
// get the iterator of for each iterables
const iters = [...iterables].map((iterable) => iterable[Symbol.iterator]());
let next = iters.map((iter) => iter.next().value);
// as long as any of the iterables returns something, yield a value (zip longest)
while(anyOf(next)) {
yield next;
next = iters.map((iter) => iter.next().value);
}
function anyOf(arr){
return arr.some(v => v !== undefined);
}
}
// put zipped result in aa array
const result = [...zip(a, new Set(b))];
// or lazy generate the values
for (const [valA, valB] of zip(a, new Set(b))) {
console.log(`${valA}: ${valB}`);
}Run Code Online (Sandbox Code Playgroud)
显然,也可以仅使用
[...Iterable]将 any 转换Iterable为数组,然后使用第一个函数。
| 归档时间: |
|
| 查看次数: |
74631 次 |
| 最近记录: |