本文介绍了这个JavaScript问题是否可能没有循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当前在代码提交网站上,它不会让我继续前进.
Currently on a code submission website and it won't let me move forward.
var filmCharacters = [
['Vito', 'Michael', 'Sonny', 'Freddo'],
['Mia', 'Vincent', 'Jules', 'Butch'],
['Bella', 'Edward', 'Jacob', 'Carlisle'],
['James', 'M', 'Moneypenny', 'Felix']
];
我最近的尝试是
for (var i = 0; i < filmCharacters.length; i++) {
for (var j = 0; j < filmCharacters[i].length; j++) {
if (filmCharacters[i][j].startsWith('M')) {
console.log(filmCharacters[i][j]);
}
}
}
推荐答案
一个 for
循环是一个循环.
如果您想使代码一目了然,我想从技术上讲,无需任何循环机制(例如递归)就可以做到:
If you wanted to make the code hard to understand at a glance, I suppose it would technically be possible to do so without any looping mechanism, such as with recursion:
var filmCharacters = [
['Vito', 'Michael', 'Sonny', 'Freddo'],
['Mia', 'Vincent', 'Jules', 'Butch'],
['Bella', 'Edward', 'Jacob', 'Carlisle'],
['James', 'M', 'Moneypenny', 'Felix']
];
const checkArr = arr => {
if (arr.length) {
checkSubarr(arr[0])
checkArr(arr.slice(1));
}
};
const checkSubarr = subarr => {
if (subarr.length) {
if (subarr[0].startsWith('M')) {
console.log(subarr[0]);
}
checkSubarr(subarr.slice(1));
}
};
checkArr(filmCharacters);
即使不允许这样做,我也认为代码确实很不错.
If even that isn't permitted, I suppose the code be really WET.
var filmCharacters = [
['Vito', 'Michael', 'Sonny', 'Freddo'],
['Mia', 'Vincent', 'Jules', 'Butch'],
['Bella', 'Edward', 'Jacob', 'Carlisle'],
['James', 'M', 'Moneypenny', 'Felix']
];
const c = filmCharacters;
const check = str => {
if (str.startsWith('M')) console.log(str);
};
check(c[0][0]);
check(c[0][1]);
check(c[0][2]);
check(c[0][3]);
check(c[1][0]);
check(c[1][1]);
check(c[1][2]);
check(c[1][3]);
check(c[2][0]);
check(c[2][1]);
check(c[2][2]);
check(c[2][3]);
check(c[3][0]);
check(c[3][1]);
check(c[3][2]);
check(c[3][3]);
但这太荒谬了.
var filmCharacters = [
['Vito', 'Michael', 'Sonny', 'Freddo'],
['Mia', 'Vincent', 'Jules', 'Butch'],
['Bella', 'Edward', 'Jacob', 'Carlisle'],
['James', 'M', 'Moneypenny', 'Felix']
];
filmCharacters
.flat()
.filter(str => str.startsWith('M'))
.forEach(x => console.log(x));
这篇关于这个JavaScript问题是否可能没有循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!