for (const item in arr) {
//其中arr是需要遍历的数组,item是arr数组对应的下标(从0开始)
//是通过arr[下标]的方式去获取数组中的元素的
console.log(arr[index]);
}
//需要注意的是,item就类似于键值对中的键,其类型为string类型,做加法运算时需要用Number进行转换一下
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>测试js中for in的用法title>
head>
<body>
<script>
var arr=[1,4,true,"123"];
// fin回车是生成for in的快捷键
for (const item in arr) {
console.log("arr数组中的第"+(Number(item)+1)+"个元素的值为: "+arr[item]);
}
script>
body>
html>
for (const item in str) {
//str是字符串
console.log("str字符串的第"+(Number(item)+1)+"个字符的值为: "+str[item]);
}
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>测试js中for in的用法title>
head>
<body>
<script>
var str="abctef7";
// fin回车是生成for in的快捷键
for (const item in str) {
console.log("str字符串的第"+(Number(item)+1)+"个字符的值为: "+str[item]);
}
script>
body>
html>
for (const item in obj) {
//其中obj是对象,item是键值对中的键(冒号前面的那部分)
console.log(item+"的值为"+obj[item]);
}
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>测试js中for in的用法title>
head>
<body>
<script>
var obj={name:'牙膏',price:12.5};
for (const item in obj) {
console.log(item+"的值为: "+obj[item]);
}
script>
body>
html>
for (const iterator of arr) {
//for of是相当于获取值,没有下标(类似java中的foreach)
console.log(iterator);
}
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>测试js中for of的用法title>
head>
<body>
<script>
var arr=[false,56,"123"];
for (const iterator of arr) {
//for of是相当于获取值,没有下标
console.log(iterator);
}
script>
body>
html>
for (const iterator of str) {
//for of是相当于获取值,没有下标,str是字符串
console.log(iterator);
}
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>测试js中for of的用法title>
head>
<body>
<script>
var str="jsdg54er"
for (const iterator of str) {
//for of是相当于获取值,没有下标
console.log(iterator);
}
script>
body>
html>
3.1.1 错误示例html代码
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>测试js中for of的用法title>
head>
<body>
<script>
var obj={name:"张三",sex:"男"};
for (const iterator of obj) {
//for of是相当于获取值,没有下标
console.log(iterator);
}
script>
body>
html>
3.1.2 错误示例运行截图
当遍历对象时,采用for in
开发当中,因地制宜(根据情况去选择)就行。