gpt4 book ai didi

JavaScript 比较数组在不应该失败的时候失败

转载 作者:行者123 更新时间:2023-12-03 04:08:22 25 4
gpt4 key购买 nike

问题:

Call two arms equally strong if the heaviest weights they each are able to lift are equal.

Call two people equally strong if their strongest arms are equally strong (the strongest arm can be both the right and the left), and so are their weakest arms.

Given your and your friend's arms' lifting capabilities find out if you two are equally strong.

问题:

My solution keeps showing false when all numbers are equal. For example, when >you = [10, 15] and friend = [10, 15], I'm getting false when it should be true.Sure it's user error over here. :)

function areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight) {
var you = [yourLeft, yourRight];
var friend = [friendsLeft, friendsRight];
you.sort(), friend.sort();
console.log(you, friend)
if(you === friend){
return true;
}else{
return false;
}
}

已解决,谢谢!!

function areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight) {
var you = [yourLeft, yourRight];
var friend = [friendsLeft, friendsRight];
you.sort(), friend.sort();
console.log(you, friend)
for(var i = 0; i < you.length; i++) {
if(you[i] !== friend[i])
return false;
}

return true;
}

最佳答案

您的问题是您试图将一个项目列表与另一个项目列表进行比较,甚至没有阅读列表中的项目。当您执行 === 时,您正在比较该项目的值,并且这不能是一个数组,因为它不够聪明,无法循环遍历所有项目并进行比较(这就是为什么对于每个存在 ;) - 所以 "10"=== "10 = true 但 ["10"] === ["10"] = false

你有一个数组,所以你需要循环并确保元素的每个索引都匹配。我假设你在两个数组中总是有相同的数字,所以你可以这样做:

function areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight) {
var you = [yourLeft, yourRight];
var friend = [friendsLeft, friendsRight];
you.sort(), friend.sort();
console.log(you, friend)
for(var i = 0; i < you.length; i++) {
if(you[i] !== friend[i])
return false;
}

return true;
}

关于JavaScript 比较数组在不应该失败的时候失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44443583/

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