1,Javascript 使用for in 遍历
Array 在 Javascript 中是一个对象, Array 的索引是属性名。此处输出的索引值,即 “0″、 “1″、 “2″不是 Number 类型的,而是 String 类型的,因为其就是作为属性输出,而不是索引
export default {
components: {},
props: {},
data() {
return {
test_list:[
10,9,8,7
],
};
},
watch: {},
computed: {},
methods: {
count(){
for(var i in this.test_list){
console.log(typeof i)
console.log("i is ",i)
if(i===0){
console.log("i is ",i)
console.log("i is number ")
}
if(i==='0'){
console.log("i is ",i)
console.log("i is string ")
}
}
}
},
created() {},
mounted() {
this.count()
},
};
控制台打印
验证 js的for in 来遍历 array ,索引取值是string。
Note: 在此情况下,若使用===来判断索引的话,一定要在===后写上判断的字符形式,若写为数字,则永远不会成立。
2,使用vue 的v-for来遍历array
<template>
<div class="">
<div v-for="(index) in test_list" :key="index">
{{ index }}
<span v-if="index===9">int</span>
<span v-if="index==='9'">string</span>
</div>
</div>
</template>
<script>
export default {
components: {},
props: {},
data() {
return {
test_list:[
10,9,8,7
],
};
},
watch: {},
computed: {},
methods: {
count(){
for(var i in this.test_list){
console.log(typeof i)
console.log("i is ",i)
if(i===0){
console.log("i is ",i)
console.log("i is number ")
}
if(i==='0'){
console.log("i is ",i)
console.log("i is string ")
}
}
}
},
created() {},
mounted() {
this.count()
},
};
</script>
<style lang=""></style>
页面打印是:
v-for遍历array取值的是array中的元素 ,类型由元素决定。
v-for也可以取到索引值:
v-for索引取的索引是int类型
<div v-for="(item,index) in test_list" :key="index">
{{item}}-索引是:{{ index }}
<span v-if="index===1">int</span>
<span v-if="index==='1'">string</span>
</div>
页面打印:
10-索引是:0
9-索引是:1 int
8-索引是:2
7-索引是:3