JavaScriptで、配列を展開してメソッドに渡す方法

1
2
3
4
5
use List::Util qw(sum);
my $array = [1, 2, 3, 4, 5];
sub func { print sum(@_); }

func(@$array); # ここで$arrayを展開している
1
2
3
4
var array = [1, 2, 3, 4, 5];
var func = function(a, b, c, d, e){ alert(a + b + c + d + e); };

func.apply(this, array); // 配列をそのまま渡しても動くという謎仕様
1
2
3
4
5
// 非同期通信
$.get(url, function(contents){
    console.debug('contents:', contents);
    /* ゴニョゴニョ */
});
1
var contents = getContentsByAjax(url);
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
'use strict';

jQuery(function($, undefined){
    var eventHoge = function(e){
        var args = Array.prototype.slice.apply(e.data);
        hoge.apply(this, args); // hogeを呼び出し
    },
    hoge = function(foo, bar){
        console.debug('hoge arguments:', arguments);
    },
    init = function(foo, bar){
        console.debug('init arguments:', arguments);
        hoge(foo, bar); // hogeを呼び出し
        $(window).one('hoge', arguments, eventHoge);
        $(window).triggerHandler('hoge');
    };
    init('foo', 'bar');
});
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
'use strict';

jQuery(function($, undefined){
    var DEBUG = 1,
    lscache,
    Mustache,
    $runButtons,
    generateKeyFromPath = function(path){
        return 'fetched:' + path;
    },
    fetchTemplate = function(path, $cb){
        var key = generateKeyFromPath(path);
        $.get(path, function(template){
            console.debug('run $.get');
            lscache.set(key, template, 1);
            return $cb.fire(template);
        });
    },
    getTemplate = function(path, $cb){
        var key = generateKeyFromPath(path);
        var template = lscache.get(key);
        if (template) {
            return $cb.fire(template);
        }
        else {
            fetchTemplate(path, $cb);
        }
    },
    render = function(targetId, targetName){
        var obj = {
            id: targetId,
            name: targetName
        };
        var $cb = $.Callbacks();
        $cb.add(function(template){
            var rendered = Mustache.render(template, obj);
            $('#' + targetId).html(rendered);
        });
        getTemplate('templates/init.mst', $cb);
    },
    changeName = function(e){
        var $this = $(e.currentTarget);
        render($this.data('id'), $this.html());
    },
    setVars = function(){
        lscache = window.lscache;
        Mustache = window.Mustache;
        $runButtons = $('button[data-run=changeName]');
    },
    initHandlers = function(){
        $runButtons.on('click', changeName);
    },
    init = function(){
        setVars();
        initHandlers();
        if (DEBUG) {
            lscache.flush();
        }
    };
    init();
});

Comments

comments powered by Disqus