[英]Is there a more javascript way to handle zipping two arrays instead of using a for loop?
This code works as intended based on the problem I am supposed to solve. 此代码基于我应该解决的问题按预期工作。 However, as I am new to JavaScript, I was curious if this is the proper way to handle zipping two arrays.
但是,由于我是JavaScript的新手,我很好奇这是否是处理压缩两个数组的正确方法。 I've already read a few examples using map which seem concise, but I am more curious if there is a generally agreed upon proper method in JavaScript to do this?
我已经阅读了一些看似简洁的地图的例子,但是如果在JavaScript中有一个普遍认同的正确方法来做这个,我会更好奇吗?
var faker = require("faker");
var products = Array.from({length:10}, () => faker.commerce.productName());
var prices = Array.from({length:10}, () => faker.commerce.price())
var strOut = "";
for(var i=0; i<10; i++){
strOut += `${products[i]} - ${prices[i]} \n`
}
console.log('====================\n'+
'WELCOME TO MY SHOP!\n'+
'====================\n'+
`${strOut}`);
const strOut = products.reduce(
(result, product, index) => `${result} ${product} ${prices[index]}\n`,
''
);
const strOut = products.map(
(product, index) => `${product} ${prices[index]}`
).join("\n");
second argument of map
's callback is the array index, you can use it for second array. map
的回调的第二个参数是数组索引,你可以将它用于第二个数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.