Add JS array values

method: 

//数组值相加
sum(arr) {

	return eval(arr.join("+"));

},

Example: Add the element values ​​in each item in the array

	var vm = new Vue({
		el: '#content',
		data: {
			allMoney: '', //总收入
            moneyList:[]
		},
		mounted() {
			this.MyMoney()
		},
		methods: {
			//我的收入
			MyMoney() {
				let sendData = {
					token: localStorage.getItem("token")
				};
				$.ajax({
					type: "post",
					url: hrefURL + 'api/haha/自己的接口',
					data: sendData,
					success: (res) => {
						if (res.code == 1) {
							console.log(res);
							res.data.forEach((item, index) => {
								this.moneyList.push(item.money)  //拿到每个item里的money值存入新数组
							})

							console.log(this.moneyList);
							console.log(this.sum(this.moneyList)); //打印调用sum函数结果

							this.allMoney = this.sum(this.moneyList) //赋值
						} else {
							layer.msg(res.msg);
						}
					},
					error(err) {
						layer.msg('Network failure; Please try again later');
					}
				});
			},
			//数组值相加
			sum(arr) {

				return eval(arr.join("+"));

			}	

		},

	})


Summarize

The addition of js array values ​​is actually the easiest to use the encapsulation function, which can be directly written in the HTML layout for calculation, or can be assigned and rendered like the example

Guess you like

Origin blog.csdn.net/z_2183441353/article/details/129361033