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

数组元素的添加

用concat()函数,可以将一个或者多个数组添加在另外一个数组上,添加后,是返回一个新的数组,而不是在原来的数组上添加

在.js文件中定义array0、array1、array2和con()事件

export default {
data: {
title: "",
array0:[
{value:"数值1"},
],
array1:[
{value:"数值2"},
],
array2:[]
},
onInit() {
this.title = this.$t('strings.world');
},
con(){
console.log("添加前数组0:"+JSON.stringify(this.array0))
console.log("添加前数组1:"+JSON.stringify(this.array1))
console.log("添加前数组2:"+JSON.stringify(this.array2))
this.array2=this.array0.concat(this.array1)
console.log("添加前数组0:"+JSON.stringify(this.array0))
console.log("添加前数组1:"+JSON.stringify(this.array1))
console.log("添加后数组2:"+JSON.stringify(this.array2))
}
}

在.hml文件绑定con()事件

<div class="container">
<div for="{{array2}}">
<text style="font-size: 60px;">
{{$item.value}}
</text>
</div>
<button on:click="con">合并数组</button>
</div>

点击按钮后,可以看到array0和array1没变,array2由空数组变成了array0和array1的相加

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

如果是要添加多个数组,在concat()函数的括号内用逗号隔开要添加的数组即可

this.array3=this.array0.concat(this.array1,this.array2)

数组元素的倒置

用reverse()函数可以对数组进行倒置

在.js文件中定义array0数组和编写click()事件

export default {
data: {
title: "",
array0:[
'a','b','c'
],
},
onInit() {
this.title = this.$t('strings.world');
},
click(){
console.log("倒置前:"+this.array0);
this.array0.reverse()
console.log("倒置后:"+this.array0)

}
}

在.hml文件中绑定click()事件

<div class="container">
<button on:click="click">合并数组</button>
</div>

点击按钮后,可以看到数组倒置前的顺序是abc,倒置后顺序变成了cba

【HarmonyOS】js文件常见的数组操作2_JSON_02

数组第一个元素的删除

用shift()函数可以将数组的第一个元素删除掉

.js文件


export default {
data: {
title: "",
array0:[
'a','b','c'
],
},
onInit() {
this.title = this.$t('strings.world');
},
click(){
console.log("删除第一个元素前:"+this.array0);
this.array0.shift()
console.log("删除第一个元素后:"+this.array0)

}
}

.hml文件

<div class="container">
<button on:click="click">点击按钮</button>
</div>

点击按钮可以看到第一个元素a以及被删除掉了

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

数组元素的截取

用slice(start,end)可以截取数组,截取之后原数组不会被改变,会返回一个新的数组

参数:

start:开始截取的索引,截取的结果包括该索引的值

end:停止截取的索引,截取的结果不包括该索引的值

.hml文件

<div class="container">
<button on:click="click">点击按钮</button>
</div>

.js文件

export default {
data: {
title: "",
array0:[
'a','b','c','d','e'
],
array1:[

]
},
onInit() {
this.title = this.$t('strings.world');
},
click(){
console.log("截取数组前:"+this.array1);
this.array1=this.array0.slice(1,3)
console.log("截取数组后:"+this.array1)

}
}

点击按钮后,可以看到截取到的数组包括array0[1]但是不包括array[3]

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


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

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

暂无评论

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