gpt4 book ai didi

javascript - 仅当在函数内部时,循环才会返回额外的时间

转载 作者:行者123 更新时间:2023-12-03 02:24:28 25 4
gpt4 key购买 nike

对此非常陌生,如果我错过了一些非常简单的东西,那么抱歉。

我一直在尝试编写一些内容,它将返回对象的属性编号、属性名称和所有属性值的列表,格式为:

"n property - property value"

我确信我已经以一种完全过于复杂的方式解决了这个问题,但这是代码:

var person = {
names: ["A", "B", "C"],
dob: "D",
age: 21,
job: "E",
car: ["F", 2, "G", "H", "I", "J", "K"],
phone: "L",
instrument: "M",
parents: ["N", "O", "P"],
born: "Q",
lives: "R",
university: "S",
};

function lister (name) {
for (i=0; i<(Object.keys(name).length); i++) {
if (((Object.values(name)[i].constructor) == Array) === true) {
for (x=0; x<(Object.keys(Object.values(name)[i]).length); x++) {
console.log(i + " " + Object.keys(name)[i] + " - " + Object.values(Object.values(name)[i])[x]);
}
}else{
console.log(i + " " + Object.keys(name)[i] + " - " + Object.values(name)[i]);
}
}
};

console.log(lister(person));

for (i=0; i<(Object.keys(person).length); i++) {
if (((Object.values(person)[i].constructor) == Array) === true) {
for (x=0; x<(Object.keys(Object.values(person)[i]).length); x++) {
console.log(i + " " + Object.keys(person)[i] + " - " + Object.values(Object.values(person)[i])[x]);
}
}else{
console.log(i + " " + Object.keys(person)[i] + " - " + Object.values(person)[i]);
}
};

问题是,当我在函数列表器(名称)中调用for循环时,它似乎额外运行了一次,给了我:

"0 names - A"

"0 names - B"

"0 names - C"

"1 dob - D"

...

"9 lives - R"

"10 university - S"

undefined

但是,当将 for 循环从函数中取出时(正如我在底部所做的那样),它会正常返回,而不返回额外的“未定义”。我做错了什么?

最佳答案

这个额外的部分不是来自循环,而是来自函数调用。如果函数没有显式返回任何内容,则返回未定义,在下面的代码片段中,函数 lister 返回 x,因此您将看到 x 而不是 undefined >

var person = {
names: ["A", "B", "C"],
dob: "D",
age: 21,
job: "E",
car: ["F", 2, "G", "H", "I", "J", "K"],
phone: "L",
instrument: "M",
parents: ["N", "O", "P"],
born: "Q",
lives: "R",
university: "S",
};

function lister(name) {
for (i = 0; i < (Object.keys(name).length); i++) {
if (((Object.values(name)[i].constructor) == Array) === true) {
for (x = 0; x < (Object.keys(Object.values(name)[i]).length); x++) {
console.log(i + " " + Object.keys(name)[i] + " - " + Object.values(Object.values(name)[i])[x]);
}
} else {
console.log(i + " " + Object.keys(name)[i] + " - " + Object.values(name)[i]);
}
}
return 'x'
};

console.log(lister(person));

for (i = 0; i < (Object.keys(person).length); i++) {
if (((Object.values(person)[i].constructor) == Array) === true) {
for (x = 0; x < (Object.keys(Object.values(person)[i]).length); x++) {
console.log(i + " " + Object.keys(person)[i] + " - " + Object.values(Object.values(person)[i])[x]);
}
} else {
console.log(i + " " + Object.keys(person)[i] + " - " + Object.values(person)[i]);
}
};

关于javascript - 仅当在函数内部时,循环才会返回额外的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49011538/

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