我只是从JavaScript开始,希望遍历数组,然后将其与2d数组中的行量值匹配。到目前为止,这是我得到的:
const relatedKeywords = ['keyword1','keyword2','keyword3'];
const relatedURLs =
[ [ 'https://en.wikipedia.org/wiki/Coffee',
'https://www.joscoffee.com/' ],
[ 'https://en.wikipedia.org/wiki/Coffee',
'https://www.joscoffee.com/' ],
[ 'https://en.wikipedia.org/wiki/Coffee',
'https://www.joscoffee.com/' ] ]
for (let y = 0; y < relatedKeywords.length; y++) {
for (let z = 0; z < relatedURLs[0].length; z++) {
console.log(relatedURLs[z].length)
}
}
这将返回2d数组中URL的数量,但是迭代6次。理想情况下,我想达到这样的输出:
Keyword1 = 2 URLs
Keyword2 = 2 URLs
Keyword3 = 2 URLs
答案 0 :(得分:0)
只需将forEach
与模板文字字符串一起使用,如下所示:
const relatedKeywords = ['keyword1', 'keyword2', 'keyword3'];
const relatedURLs = [
['https://en.wikipedia.org/wiki/Coffee',
'https://www.joscoffee.com/'
],
['https://en.wikipedia.org/wiki/Coffee',
'https://www.joscoffee.com/'
],
['https://en.wikipedia.org/wiki/Coffee',
'https://www.joscoffee.com/'
]
];
relatedKeywords.forEach((item, index) => {
console.log(`${item} = ${relatedURLs[index].length} URLs`);
});
您是否需要ES5语法:
const relatedKeywords = ['keyword1', 'keyword2', 'keyword3'];
const relatedURLs = [
['https://en.wikipedia.org/wiki/Coffee',
'https://www.joscoffee.com/'
],
['https://en.wikipedia.org/wiki/Coffee',
'https://www.joscoffee.com/'
],
['https://en.wikipedia.org/wiki/Coffee',
'https://www.joscoffee.com/'
]
];
relatedKeywords.forEach(function(item, index) {
console.log(item + " = " + relatedURLs[index].length + " URLs");
});
具有for
循环:
const relatedKeywords = ['keyword1', 'keyword2', 'keyword3'];
const relatedURLs = [
['https://en.wikipedia.org/wiki/Coffee',
'https://www.joscoffee.com/'
],
['https://en.wikipedia.org/wiki/Coffee',
'https://www.joscoffee.com/'
],
['https://en.wikipedia.org/wiki/Coffee',
'https://www.joscoffee.com/'
]
];
for (var index = 0; index < relatedKeywords.length; index++) {
let item = relatedKeywords[index];
console.log(item + " = " + relatedURLs[index].length + " URLs");
}
答案 1 :(得分:0)
我将只使用数组映射并按照所需的方式对其进行处理
const relatedKeywords = ['keyword1','keyword2','keyword3'];
const relatedURLs =
[ [ 'https://en.wikipedia.org/wiki/Coffee',
'https://www.joscoffee.com/' ],
[ 'https://en.wikipedia.org/wiki/Coffee',
'https://www.joscoffee.com/' ],
[ 'https://en.wikipedia.org/wiki/Coffee',
'https://www.joscoffee.com/' ] ]
relatedKeywords.map(function(value,index) {
console.log(value + ' = ' + relatedURLs[index].length + ' URLs');
});