关于微信小程序开发中如何动态的往数组中添加对象,并进行更改

关于微信小程序开发中如何动态的往数组中添加对象,并进行更改,第1张

因为以前都是用Vue开发,写项目,自然而然的就习惯了vue的双向绑定机制,开发中也觉得这真是方便,但是在最近的小程序开发中,我在动态往数组中传值,可是吃尽了苦头,怎么绑都绑定不上。当然,也并不是再说小程序的不好,各有各的开发理念,各有各的好,所以在这里写下一些心得,一方面让自己别忘了,一方面也希望和我一起遇到这个问题的小伙伴们,别再走这个坑!

言归正传:

加入此刻我的data中,有一个数组

然后我定义了一个方法,需要往这个lists数组中动态的添加数据

这个方法是可以往data中的lists中添加对象的,这我相信大家都能做得到,很简单

但是,当我们要改变这个lists中某个对象下的key:value值呢?当时我就在这里卡了好久,我一开始想的的是在this.setData()这个函数中,把key值改为 lists[下标].属性值 但是当我这样写了以后,控制台立马报错,原因是因为,他在data中并没有找到你这个key值,也就是说我们这个写的方法是错误的,但是按照道理思路是没错的,所以也就有了下面这个方法,可以改变对应的lists里面的属性值

这样就可以了,就能改变data中数组里面任意的值,不过要谨记一点,就是,一定要拿中括号[xx]包裹你要改变的key值,不然也是会报错的!好了,其实我感觉我说了很多没必要的话,但是,我就当记笔记了!希望大家和自己继续努力,学习永无止境【点击了解更多加盟项目】

你那样定义后,不能直接使用,因为未对当前数组变量进行实例化,也就没有进行内存分配这里给你推荐两种方法。1、初始化时设置他的数组大小string[] myarr = new string[2]myarr[0] = "1"myarr[1]="第二个值"2、初始化时设置他的数组大小并赋值string[] myarr = new string[]{"1","2"}3、可以动态改变数组大小的数组List<string>listArr = new List<string>()listArr.add("添加的值")listArr.add("再添加一个值")listArr.add("OK")listArr.RemoveAt(1)//删除索引1的项....//该方法 *** 作数组更加灵活。如果不需要动态 *** 作数组的话,可以不使用该方法。string[] myarr = listArr.ToArray()//将List类型转成string[]类型的数组

js动态添加数组可以按下面的步骤:

1、在数组的开头添加新元素 - unshift()

源代码:

<!DOCTYPE html>

<html>

<body>

<p id="demo">Click the button to add elements to the array.</p>

<button onclick="myFunction()">Try it</button>

<script>

function myFunction()

{

var fruits = ["Banana", "Orange", "Apple", "Mango"]

fruits.unshift("Lemon","Pineapple")

var x=document.getElementById("demo")

x.innerHTML=fruits

}

</script>

<p><b>Note:</b>The unshift() method does not work properly in Internet Explorer 8 and earlier, the values will be inserted, but the return value will be <em>undefined</em>.</p>

</body>

</html>

测试结果:

Lemon,Pineapple,Banana,Orange,Apple,Mango

2、在数组的第2位置添加一个元素 - splice()

源代码:

<!DOCTYPE html>

<html>

<body>

<p id="demo">Click the button to add elements to the array.</p>

<button onclick="myFunction()">Try it</button>

<script>

function myFunction()

{

var fruits = ["Banana", "Orange", "Apple", "Mango"]

fruits.splice(2,0,"Lemon","Kiwi")

var x=document.getElementById("demo")

x.innerHTML=fruits

}

</script>

</body>

</html> 

测试结果:

Banana,Orange,Lemon,Kiwi,Apple,Mango

3、数组的末尾添加新的元素 - push()

源代码:

<!DOCTYPE html>

<html>

<body>

<p id="demo">Click the button to add a new element to the array.</p>

<button onclick="myFunction()">Try it</button>

<script>

var fruits = ["Banana", "Orange", "Apple", "Mango"]

function myFunction()

{

fruits.push("Kiwi")

var x=document.getElementById("demo")

x.innerHTML=fruits

}

</script>

</body>

</html>

测试结果:

Banana,Orange,Apple,Mango,Kiwi


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/bake/11681949.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-17
下一篇2023-05-17

发表评论

登录后才能评论

评论列表(0条)

    保存