【HarmonyOS】js文件常见的数组操作1
  f98gB1FgZflj 2023年11月02日 53 0

数组长度的读取

数组长度的获取只需要在数组的后面加.length,就行

在.js文件中定义一数组array,并且编写getArrayLength()事件,其中,在getArayLength事件里面的this.array指的是data里面定义的array,this.array.length则是表示this.array的长度,返回值的类型是number

export default {
data: {
title: "",
array:[
{value:1},
{value:1},
]
},
onInit() {
this.title = this.$t('strings.world');
},
getArrayLength(){
console.log("数组的长度为:"+this.array.length)
}
}

在.hml绑定getArrayLength()点击事件

<div class="container">
<button onclick="getArrayLength">获得数组长度</button>
</div>

点击按钮后便获得数组的长度

【HarmonyOS】js文件常见的数组操作1_JSON

数组元素的打印

用toString()函数就可以将数组的内容打印出来,但是当数组的元素是对象时,改函数就不起作用

首先在.js文件定义一个array,编写ArrayToString()事件

export default {
data: {
title: "",
array:[1,2,3,4,5]
},
onInit() {
this.title = this.$t('strings.world');
},
ArrayToString(){
console.log("数组为:"+this.array.toString())
}
}

然后在.hml绑定ArrayToString()事件

<div class="container">
<button notallow="ArrayToString">打印数组</button>
</div>

点击button后可以看到数组打印了出来

【HarmonyOS】js文件常见的数组操作1_数组_02

但是当数组的元素是object时,打印出来的结果是这样的

【HarmonyOS】js文件常见的数组操作1_数组_03

若想打印元素是对象的数组,就先要将数组转换成JSON格式再打印,那ArrayToString()事件应该修改成这样,JSON.stringify(this.array)的作用就是将数组转化成JSON格式,再转化成string输出

export default {
data: {
title: "",
array:[
{value:1},
{value:1},
{value:1},
]
},
onInit() {
this.title = this.$t('strings.world');
},
ArrayToString(){
console.log("数组为:"+JSON.stringify(this.array))
}
}

点击button之后,便可以将数组打印出来

【HarmonyOS】js文件常见的数组操作1_JSON_04

数组元素的删除

使用pop()函数,就可以删除数组最后的元素

在.js文件中定义delete()事件,调用数组pop()函数

export default {
data: {
title: "",
array:[
{value:"数值1"},
{value:"数值2"},
{value:"数值3"},
]
},
onInit() {
this.title = this.$t('strings.world');
},
delete(){
console.log("删除前:"+JSON.stringify(this.array))
this.array.pop()
console.log("删除后:"+JSON.stringify(this.array))
}
}

然后在.hml文件中绑定delete事件

<div class="container" on:click="delete">
<div for="{{array}}">
<text style="font-size: 60px;">
{{$item.value}}
</text>
</div>
</div>

点击屏幕后,可看到最后一个元素已被删除

【HarmonyOS】js文件常见的数组操作1_数组_05

数组元素的添加

用push()函数,可以在数组的后面添加元素

在.js文件里面编写add()事件,调用数组的push()函数,push()函数的括号里面是要添加进数组的元素

export default {
data: {
title: "",
array:[
{value:"数值1"},
{value:"数值2"},
{value:"数值3"},
]
},
onInit() {
this.title = this.$t('strings.world');
},
add(){
console.log("添加前:"+JSON.stringify(this.array))
this.array.push({value:"增加的元素"})
console.log("添加后:"+JSON.stringify(this.array))
}
}

然后在.xml文件里面绑定add()事件

<div class="container" on:click="add">
<div for="{{array}}">
<text style="font-size: 60px;">
{{$item.value}}
</text>
</div>
</div>

点击屏幕后可以看到添加了一个元素进去

【HarmonyOS】js文件常见的数组操作1_数组长度_06


【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  gBkHYLY8jvYd   2023年12月10日   24   0   0 #include数组i++
f98gB1FgZflj