gpt4 book ai didi

javascript - isEqual 函数总是返回 true

转载 作者:行者123 更新时间:2023-12-03 05:23:15 26 4
gpt4 key购买 nike

此函数检查两个对象是否具有相同的值:

_.isEqual = (a, b) => {
const aKeys = Object.getOwnPropertyNames(a)
const bKeys = Object.getOwnPropertyNames(b)
if (aKeys.length !== bKeys.length) {
return false
}
for (var i = 0; i < aKeys.length; i++) {
var propName = aKeys[i]
if (a[propName] !== b[propName]) {
return false
}
}
return true
}

我用 every 替换了 for 循环:

_.isEqual = (a, b) => {
const aKeys = Object.getOwnPropertyNames(a)
const bKeys = Object.getOwnPropertyNames(b)
if (aKeys.length !== bKeys.length) return
return aKeys.every((key, index) => {
return key === bKeys[index]
})
}

但是,即使 a 和 b 不相等,该函数也会返回 true

我做错了什么?

输入:

const obj1 = {
x: 0,
y: 0,
z: 0
}

const obj2 = {
x: 0,
y: 0,
z: 0
}

最佳答案

var first = "hello"
var second = "meow"

console.log("recognized")

isEqual(first,second);

function isEqual(a, b) {
console.log("running")
const aKeys = Object.getOwnPropertyNames(a)
const bKeys = Object.getOwnPropertyNames(b)
if (aKeys.length !== bKeys.length) {
console.log("false")
return false
}
for (var i = 0; i < aKeys.length; i++) {
var propName = aKeys[i]
if (a[propName] !== b[propName]) {
console.log("false")
return false
}
}
console.log("return true")
return true
}

如果我更改 second 则打印出 false至hello ,它会打印出true。我想说这与您的输入数据有关。您是否尝试过使用较小的输入数据集来确保一切正常?

更新:或者您的问题仅与第二次交互有关?如果是这样的话,你有两个 return声明

var first = ["shoop", "doop", "woop", "loop", "koop"]
var second = ["hamp","damp", "samp", "wamp"]

console.log("recognized")

var returned = isEqual(first,second);

console.log(returned)

function isEqual(a, b) {
const aKeys = Object.getOwnPropertyNames(a)
const bKeys = Object.getOwnPropertyNames(b)
if (aKeys.length !== bKeys.length) {
return aKeys.every((key, index) => {
key === bKeys[index]
})
}
}

这可能就是您正在寻找的。如果akeybkey长度不等于 every方法将执行其操作并返回 false在本例中为 keybkey不等于 false被返回。 if (aKeys.length !== bKeys.length)不是真的,undefined将按照js的本质返回

为了回应评论“如何通过返回 true 或 false 来完成”,您可以返回 true如果 if 语句从未运行,即 bkeys.length等于akeys.length

var first = ["shoop", "doop", "woop", "loop"]
var second = ["hamp","damp", "samp", "wamp"]

console.log("recognized")

var returned = isEqual(first,second);

console.log(returned)

function isEqual(a, b) {
const aKeys = Object.getOwnPropertyNames(a)
const bKeys = Object.getOwnPropertyNames(b)
if (aKeys.length !== bKeys.length) {
return aKeys.every((key, index) => {
key === bKeys[index]
})
}
else{
return true
}
}

关于javascript - isEqual 函数总是返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41275089/

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