gpt4 book ai didi

javascript - 计算数组中的元素并比较它们,javascript

转载 作者:行者123 更新时间:2023-11-28 06:11:04 25 4
gpt4 key购买 nike

我正在尝试用我非常有限的 Javascript 知识来解决问题。

我尝试构建一种方法来计算特定字母在数组中出现的次数,并将其与另一个字母在同一数组中出现的次数进行比较。

我能够通过 4 次测试中的 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;
}
}

最佳答案

这是我的做法:

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

关于javascript - 计算数组中的元素并比较它们,javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36388779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com