gpt4 book ai didi

Javascript for循环变量范围?

转载 作者:行者123 更新时间:2023-11-30 08:27:14 24 4
gpt4 key购买 nike

<分区>

我来自 C++ 背景并且是 java 脚本的新手并且难以理解循环范围。 for 循环中初始化的变量作用域是什么。

//Setup
var contacts = [
{
"firstName": "Akira",
"lastName": "Laine",
"number": "0543236543",
"likes": ["Pizza", "Coding", "Brownie Points"]
},
{
"firstName": "Harry",
"lastName": "Potter",
"number": "0994372684",
"likes": ["Hogwarts", "Magic", "Hagrid"]
},
{
"firstName": "Kristian",
"lastName": "Vos",
"number": "unknown",
"likes": ["Javascript", "Gaming", "Foxes"]
}
];


function lookUpProfile(firstName, prop){
for(var i=0;i<contacts.length;i++){
if(contacts[i].firstName==firstName){
if(contacts[i].hasOwnProperty(prop))
return contacts[i][prop];
else
return "No such property";
}
}

if (i === contacts.length)
return "No such contact";

}

// Change these values to test your function
lookUpProfile("Akira", "likes");

我很困惑 if (i === contacts.length) 变量“i”是如何在 for 循环外使用的,变量“i”是如何在 for 循环内初始化的,if 语句是从for循环的作用域。 document.write(i) 的值在循环外打印时等于 4。有人可以解释一下吗?

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