gpt4 book ai didi

javascript - 如何执行我的代码以获得想要的结果

转载 作者:行者123 更新时间:2023-11-29 17:33:58 25 4
gpt4 key购买 nike

我创建了一个包含对象的数组,

我在我的数组上循环,对于包含 y == 5 的对象,我影响对象的 bool 变量,然后我通过条件阻止访问,

但是我看到下一个数组中的同一个对象受到同一个 bool 变量的影响,并且我的控制台日志显示影响只按时执行,如何阻止对下一个数组元素的影响?

代码

  test: function(req, res){

console.log("yesss")
var a = {x:1}
let b = {x:2}
let c = {x:3}
let d = {x:4}

let tab1 = []
a.y = 5
b.y = 10
c.y = 10
d.y = 10
let group1 = [a, c, d]

let group2 = [a, b, d]


tab1.push(group1)
tab1.push(group2)


let test = false
async.each(tab1, function(group, next){

group.forEach(function(elem){

if(elem.y == 5 && !test)
{
console.log("******* executed ******")
test = true
elem.bool = true
}
console.log("elem : ", elem)

})

next()
}, function(){

return res.status(200).json({success: true, data: tab1})
})
},

这是我的控制台日志

控制台日志

    ******* executed ******
elem : { x: 1, y: 5, bool: true }
elem : { x: 3, y: 10 }
elem : { x: 4, y: 10 }
elem : { x: 1, y: 5, bool: true }
elem : { x: 2, y: 10 }
elem : { x: 4, y: 10 }

JsonReturn

{
"success": true,
"data": [
[
{
"x": 1,
"y": 5,
"bool": true
},
{
"x": 3,
"y": 10
},
{
"x": 4,
"y": 10
}
],
[
{
"x": 1,
"y": 5,
"bool": true
},
{
"x": 2,
"y": 10
},
{
"x": 4,
"y": 10
}
]
]
}

最佳答案

group1group2 是引用相同对象的数组,使用 JSON.parse()JSON.stringify 制作副本() :

let group1 = JSON.parse(JSON.stringify([a, c, d]));

let group2 = JSON.parse(JSON.stringify([a, b, d]));

关于javascript - 如何执行我的代码以获得想要的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58977537/

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