我正在尝试使用我对Javascript的非常有限的知识来解决问题。
我试图建立一种方法来计算一个特定字母在数组中出现的次数,并将其与另一个字母出现在同一个数组中的次数进行比较。
我能够通过3次测试,并且尝试了多次尝试尽可能多的方法。
我意识到我所做的事情并不高效......只需要用数周的技能解决问题。
感谢任何输入。感谢。
function isValidWalk(walk) {
var north = new Object ();
var south = new Object ();
var east = new Object ();
var west = new Object ();
for (var i = 0; i <walk.length; i++){
if (walk[i] == "n")
{north.input = "x"}
}
for (var i = 0; i <walk.length; i++){
if (walk[i] == "s")
{south.input = "x"}
}
for (var i = 0; i <walk.length; i++){
if (walk[i] == "e")
{east.input = "x"}
}
for (var i = 0; i <walk.length; i++){
if (walk[i] == "w")
{west.input = "x"}
}
if (north.input == south.input && east.input == west.input && walk.length==10) {
return true;
}
else {
return false;
}
}
答案 0 :(得分:0)
我将如何做到这一点:
function isValidWalk(walk) {
var steps = {n: 0, s: 0, e: 0, w: 0};
for (var i=0, l=walk.length; i<l; i++) {
if (steps.hasOwnProperty(walk[i])) {
steps[walk[i]]++;
} else {
return false; // The element is not "n","s","e", or "w"
}
}
return (steps.n == steps.s && steps.e == steps.w && walk.length == 10);
}
console.log( isValidWalk(['n','n','n','s','n','s','n','s','n','s']) ); // returns false
console.log( isValidWalk(['n','n','n','s','s','s','n','s']) ); // returns false
console.log( isValidWalk(['n','gg','hh','s','s','s','n','s','n','n']) ); // returns false
console.log( isValidWalk(['n','n','n','s','s','s','n','s','n','s']) ); // returns true