[英]How to access variable value inside a function in javascript
I have searched on the website for solutions, but I have had no luck.我在网站上搜索了解决方案,但我没有运气。 I need to make this data global.
我需要使这些数据全球化。 My code is present below:
我的代码如下:
function val() {
var plans = @json($plans);
var id = document.getElementById("plan_id").value;
plans.forEach(function(element) {
if (id == element.id) {
var i = element.amount;
return i;
}
});
}
var obj = val()
console.log(obj)
After I log that, it wont give any values but if I log inside the foreach, I will get the amount.在我记录之后,它不会给出任何值,但如果我在 foreach 中登录,我会得到金额。 Pls how can I access data inside foreach
请问如何访问foreach中的数据
Your function needs to return a value if you want to log it outside like this.如果你想像这样在外面记录,你的 function 需要返回一个值。
function val() {
const plans = @json($plans);
const id = document.getElementById("plan_id").value;
return plans
.filter(element => id === element.id)
.map(element => element.amount);
}
const obj = val()
console.log(obj)
You are not returning anything from the function and return
inside forEach
is always undefined
.您没有从 function 中
return
任何内容,并且在forEach
中返回始终为undefined
。 Use find
使用
find
function val() { var plans = @json($plans); var id = document.getElementById("plan_id").value; return plans.find(element => id === element.id).amount; } var obj = val() console.log(obj)
This would on change get the amountValue from based on what ID you have selected.这将根据您选择的 ID 更改从中获取 amountValue。
var amountValue = null;
function val() {
var plans = @json($plans);
var id = document.getElementById("plan_id").value;
for (i = 0; i < plans.length; i++) {
if (id === plans[i].id) {
amountValue = plans[i].amount;
return amountValue;
}
}
}
var obj = val()
console.log(obj)
Thanks everyone, I have fixed my issue, but I follow another process.谢谢大家,我已经解决了我的问题,但我遵循另一个过程。
I actually get the amount using onclick我实际上使用 onclick 得到了金额
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.