gpt4 book ai didi

javascript - 脱离 for 循环

转载 作者:行者123 更新时间:2023-12-01 02:48:52 27 4
gpt4 key购买 nike

我正在尝试创建一个函数,以便您可以循环遍历一个包含很多对象的大对象,并按值找到特定的方法。我想在使用break语句找到值时停止函数中的循环。这是我的代码。

let fake_window = {
aaa: "aaa",
bbb: "bbb",
ccc: "ccc",
ddd: function ddd() {
console.log('ddd');
},
eee: {
eea: "eea",
eeb: "eeb",
eec: "eec"
},
fff: {
ffa: "ffa",
ffb: "ffb",
ffc: {
fac: "fac",
fbc: "fbc",
fcc: "fcc",
fdc: "fdc"
}
},
ggg: {
gga: {
gaa: "gaa",
gba: "gba"
},
ggb: "ggb"
}

};

const window_loop = function (window_obj, value) {
for (const prop in window_obj) {
if (window_obj.hasOwnProperty(prop)) {
if (value) {
if (value === window_obj[prop]) { // when value is found
console.log("FOUND, NOW STOP!");
break;
}
}
console.log(prop + ' => ' + window_obj[prop]);
if (typeof window_obj[prop] === "object") {
window_loop(window_obj[prop], value);
}
}
}
};

window_loop(fake_window, 'fbc');

当找到该值时,我会安慰“找到了,现在停止!”然后我打破循环。但由于某种原因,循环不断迭代。有人可以帮我解释为什么会发生这种情况吗?

最佳答案

您的问题是,当递归调用 window_loop 时,会达到 fbc 值,并且 window_loop 的返回值不用于破坏外部循环。

您可以对 window_loop 方法进行一些更改(内联注释)

window_loop = function (window_obj, value) {
var isFound = false; //new flag is introduced
for (const prop in window_obj) {
if (window_obj.hasOwnProperty(prop)) {
if (value) {
if (value === window_obj[prop]) { // when value is found
console.log("FOUND, NOW STOP!");
isFound = true;
break;
}
}
console.log(prop + ' => ' + window_obj[prop]);
if (typeof window_obj[prop] === "object") {
isFound = window_loop(window_obj[prop], value);
if ( isFound ) //break when returned value from loop is true
{
break;
}
}
}
}
return isFound; //return this value
};

另一种简洁的方法是

var window_loop = function (window_obj, value) {
//return the value of find
return Object.keys( window_obj ).find( function( key ){
if (typeof window_obj[key] === "object") {
//invoke window_loop recursively if the value is object.
return window_loop(window_obj[key], value);
}
if ( value == key )
{
console.log("FOUND, NOW STOP!", key);
}
else
{
console.log("Not FOUND, continue !", key);
}
return value == key;
})
};

演示

var fake_window = {
aaa: "aaa",
bbb: "bbb",
ccc: "ccc",
ddd: function ddd() {
console.log('ddd');
},
eee: {
eea: "eea",
eeb: "eeb",
eec: "eec"
},
fff: {
ffa: "ffa",
ffb: "ffb",
ffc: {
fac: "fac",
fbc: "fbc",
fcc: "fcc",
fdc: "fdc"
}
},
ggg: {
gga: {
gaa: "gaa",
gba: "gba"
},
ggb: "ggb"
}

};

var window_loop = function (window_obj, value) {
return Object.keys( window_obj ).find( function( key ){
if (typeof window_obj[key] === "object") {
return window_loop(window_obj[key], value);
}
if ( value == key )
{
console.log("FOUND, NOW STOP!", key);
}
else
{
console.log("Not FOUND, continue !", key);
}
return value == key;
})
};

window_loop(fake_window, 'fbc');

关于javascript - 脱离 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47096929/

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