我有这个带有变量value_from_db
for (var i = 0; i < arrayLength; i++) {
var value_from_db = array[i].value;
}
但是我需要使变量value_from_db_0、value_from_db_1、value_from_db_2
...取决于i。
类似于:
var value_from_db_+i = array[i].value;
目的是
for (var i = 0; i < arrayLength; i++) {
if( array[i].condition == '0' ) {
jQuery("#username").on('change', function() {
var value = this.value;
if( value === array[i].value ) { //because array[i].value doesnot seem to work here
count++;
alert(count);
}
}
}
因为 array[i].value 似乎没有通过匿名函数,所以我试图区分变量。
最佳答案
这里有几个选择。第一个明显的方法是使用数组:
var value_from_db = array.map(item => item.value)
// then access them with the index directly
console.log(value_from_db[0])
但是如果您确实想要这些变量名称,您可以相当轻松地将它们容纳在一个对象中:
var myObj = {}
array.forEach((item, i) => myObj[`value_from_db_${i}`] = item.value)
// the use with something like
console.log(myObj.value_from_db_0)
<小时/>
阅读完 @Igors 闭包答案的评论后,看起来您正在尝试做的事情(这是从模糊评论中最好的猜测),是监视 #username
的更改,并且弄清楚所有数组值是否在某一点或另一点都匹配。如果我是对的,你可以这样做:
// remove unwanted condition items
var conds = array.filter(item => item.condition === '0')
// watch for element changes
jQuery("#username").on('change', function() {
var comparer = this.value
// update a match key for any items where a match is found
conds
.filter(item => item.value === comparer)
.forEach(item => item.match = true)
// check if all matches have been found
if(conds.every(item => item.match)){
alert('all matched')
}
})
关于javascript - 连接另一个变量时初始化一个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49472000/