jQuery 将数组作为函数中的参数传递

San*_*nya 4 arrays jquery

我正在尝试将数组作为函数中的参数传递

请参阅 -->小提琴<--

根据我的测试,该函数似乎将参数读取为字符串而不是数组。如何将数组作为函数中的参数传递?

超文本标记语言

<button id='arr1'>Click for Array 1</button>
<button id='arr2'>Click for Array 2</button><br/><br/>

<div id='mainstuff'>
    <p>When you click button, text should be added</p>
</div>
Run Code Online (Sandbox Code Playgroud)

jQuery

$(document).ready(function() {
    var arr1 = ["one", "two", "three"];
    var arr2 = ["eleven", "twelve", "thirteen", "fourteen"];

    $('button').click(function() {
        var myval = $(this).attr('id');
        showstuff(myval);        
    });


    function showstuff(myval) {
        var x = "<p>The new text is " + myval[2] + "</p>";
        $('#mainstuff').append(x);
    }

});
Run Code Online (Sandbox Code Playgroud)

编辑:Fiddle 已更新以修复语法错误。

lon*_*day 5

你不应该这样做。不要尝试动态调用变量,即在不知道变量名称的情况下。在某些情况下,您可以立即执行此操作,但这是一个坏主意。

这里最好的解决方案是使用对象和方括号表示法从对象动态获取值:

var values = {
    arr1: ["one", "two", "three"],
    arr2: ["eleven", "twelve", "thirteen", "fourteen"]
}

$('button').click(function() {
    var myval = this.id;
    showstuff(values[myval]);        
});
Run Code Online (Sandbox Code Playgroud)

请注意,我已更改$(this).attr('id')this.id大幅提高性能。