V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
soooulp
V2EX  ›  问与答

如何在数组内一个元素引用另一个元素?

  •  
  •   soooulp · 2021-01-30 16:52:01 +08:00 · 896 次点击
    这是一个创建于 1174 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我想将每个图标打开的次数分别存储在油猴里面,建了一个数组分别存放图标的名称、图片、链接、弹出的信息,弹出的信息是一个函数,点击图标时执行打开链接和统计次数

    我需要在函数里面引用当前的图标的名称,如何通过 JavaScript 实现呢?或者是否有其他的办法?

    在这个脚本基础上改的 https://greasyfork.org/zh-CN/scripts/404859

     var iconArray = [
            {
                name: 'Google',
                image: 'https://i.ibb.co/R9HMTyR/1-5.png',
                host: ['www.google.com'],
                popup: function (text, name) {
                    open('https://www.google.com/s?wd=' + encodeURIComponent(text), name);
                    console.log(name);
                }
            },
            {
                name: 'Bing',
                image: 'https://i.ibb.co/R9HMTyR/1-5.png',
                host: ['www.bing.com'],
                popup: function (text, name) {
                    open('https://www.bing.com/s?wd=' + encodeURIComponent(text), name);
                    console.log(name);
                }
            },
        ]
    
    function open(url, a) {
             try {
                 if(GM_openInTab(url, { loadInBackground: true, insert: true, setParent :true })){
    
                        if(GM_getValue(a).times){
                            GM_setValue(a, {
                                'times': GM_getValue(a).times + 1
                            });
                        }else{
                            GM_setValue(a, {
                                'times': 1
                            });
                        }
                        console.log('times-'+GM_getValue(a).times);
    
                 } else{
    
                 }
             } catch (error) {
                 return GM_openInTab(url, { loadInBackground: true, insert: true, setParent :true });
             }
        }
    

    我想在油猴里面这样存放数据,打开 Google 1 次,Bing 4 次

    {
        "Google": {
            "times": "1",
        },
        "Bing": {
            "times": "4",
        },
          
    }
    
    第 1 条附言  ·  2021-01-30 21:27:20 +08:00
    通过调用 popup 的时候传入 name 解决啦
    1 条回复    2021-01-30 16:58:55 +08:00
    AndyAO
        1
    AndyAO  
       2021-01-30 16:58:55 +08:00
    前几天我想在 Json 中这么做
    但搜索之后发现是不行的
    如果非要这么做的话,可以先定规则,再解析
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3273 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 12:22 · PVG 20:22 · LAX 05:22 · JFK 08:22
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.