使用传递给函数的值访问JavaScript数组(Accessing a JavaScript array using a value passed into a function)

编程入门 行业动态 更新时间:2024-10-26 09:34:19
使用传递给函数的值访问JavaScript数组(Accessing a JavaScript array using a value passed into a function)

我在我的JavaScript页面中声明了一个JavaScript数组,如下所示:

var example = [[20,870,5,1,1,16],[28,1250,8,1,1,23]];

这在其他地方访问时工作正常。

我的HTML页面中有一个复选框,如下所示:

<input type="checkbox" id="example" onChange="update('example')">Example

我希望函数看起来像下面的东西。 传递的变量也是我的JS数组的名称。 我将有20-30个复选框,我希望避免加载if / else语句。

function update(a) { alert(a[0][1]); }

反正有没有使用传递给我的函数的变量来访问同名的JS数组?

谢谢

I have a JavaScript array declared in my JavaScript page like so:

var example = [[20,870,5,1,1,16],[28,1250,8,1,1,23]];

This works fine when accessed elsewhere.

I have a checkbox in my HTML page like so:

<input type="checkbox" id="example" onChange="update('example')">Example

I want the function to look something like below. The variable being passed is also the name of my JS array. I will have 20-30 check boxes and I would ideally like to avoid a load of if/else statements.

function update(a) { alert(a[0][1]); }

Is there anyway to use the variable passed into my function to access the namesake JS array?

Thanks

最满意答案

如果定义了example则可以在update(example)调用时删除围绕参数example引号

<script>
  var example = [
    [20, 870, 5, 1, 1, 16],
    [28, 1250, 8, 1, 1, 23]
  ];

  function update(a) {
    alert(a[0][1]);
  }
</script>

<input type="checkbox" id="example" onchange="update(example)">Example 
  
 

If example is defined, you can remove quotes surrounding parameter example at update(example) call

<script>
  var example = [
    [20, 870, 5, 1, 1, 16],
    [28, 1250, 8, 1, 1, 23]
  ];

  function update(a) {
    alert(a[0][1]);
  }
</script>

<input type="checkbox" id="example" onchange="update(example)">Example 
  
 

更多推荐

本文发布于:2023-07-29 14:10:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1316765.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   函数   JavaScript   Accessing   passed

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!