我正在开展学校项目
如何访问变量名称并将其存储在另一个变量ex:y [i]。
中在javascript代码中用什么来代替评论。
var p = ["a","b","d"];
var q = ["d","b","c"];
var value = "d";
var x = [];
var y = [];
function testArrays(needle, arrays) {
for (var i=0; i<arrays.length; i++) {
x[i] = arrays[i].indexOf(value);
// y[i] = // store array`s name here
}
document.getElementById("demo").innerHTML = x + y;
}
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<p>Click the button to display the position of the element "Apple":</p>
<button onclick="testArrays(value, [p, q])">Try it</button>
<p id="demo"></p>
</body>
</html>
答案 0 :(得分:1)
以下是您搜索的内容:您必须使用数组构造一个对象并传递所有数组。
var obj = {
p:["a","b","d"],
q: ["d","b","c"]
};
var value = "d";
var x = [];
var y = [];
function testArrays(needle, arrays) {
for(key in arrays){
x.push(arrays[key].indexOf(value));
y.push(key);
}
document.getElementById("demo").innerHTML = x + y;
}
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<p>Click the button to display the position of the element "Apple":</p>
<button onclick="testArrays(value, obj)">Try it</button>
<p id="demo"></p>
</body>
</html>
答案 1 :(得分:0)
因为你问我在说什么。我会给你代码。 再次,为了重新迭代我的观点,你无法得到变量名。但是如果你必须以某种方式获得变量,你可以通过将所有需要访问的变量放在一个对象中来解决。
您不会获得对象的变量名称,但您可以访问此对象的所有属性名称。
Here is the codepen link to see the code running.
HTML
<p id="test"><p>
JS
var variableList = {};
variableList.var1 = 1;
variableList.var2 = -50;
variableList.var3 = [2,4];
variableList.var4 = "4";
variableList.var5 = 5.5;
var ele = document.getElementById("test");
for(var propertyName in variableList) {
ele.innerHTML = ele.innerHTML + "<br>" + propertyName + " : " + variableList[propertyName];
}