草庐IT

javascript - 未捕获的类型错误 : undefined is not a function - typeahead. js

coder 2024-05-16 原文

我正在尝试获得一个基本的 typeahead.js example上类。如果我在单独的 HTML 文件中创建该示例,如下所示。

<html>
<head>
<script type="text/javascript" src="/static/js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="/static/js/bootstrap.min.js"></script>
<script type="text/javascript" src="/static/js/typeahead.bundle.min.js"></script>

<script type="text/javascript">
    $(document).ready(function() {
        var substringMatcher = function(strs) {
          return function findMatches(q, cb) {
            var matches, substringRegex;

            // an array that will be populated with substring matches
            matches = [];

            // regex used to determine if a string contains the substring `q`
            substrRegex = new RegExp(q, 'i');

            // iterate through the pool of strings and for any string that
            // contains the substring `q`, add it to the `matches` array
            $.each(strs, function(i, str) {
              if (substrRegex.test(str)) {
                // the typeahead jQuery plugin expects suggestions to a
                // JavaScript object, refer to typeahead docs for more info
                matches.push({ value: str });
              }
            });

            cb(matches);
          };
        };

        var djs = ['Hardwell', 'Armin van Buuren', 'Avicii', 'Tiesto', 'David Guetta', 
                   'Dimitri Vegas & Like Mike', 'Nicky Romero', 'Steve Aoki', 'Afrojack', 
                   'Dash Berlin', 'Skrillex', 'Deadmau5', 'Alesso', 'W&W', 'Calvin Harris', 
                   'NERVO', 'Above & Beyond', 'Sebastian Ingrosso', 'Axwell', 'Aly & Fila', 
                   'Markus Schulz', 'Daft Punk', 'Headhunterz', 'Zedd', 'Knife Party', 
                   'Swedish House Mafia', 'Showtek', 'Andrew Rayel', 'Fedde Le Grand', 
                   'Dyro', 'Laidback Luke', 'Paul van Dyk', 'ATB', 'Angerfist', 'Dada Life',
                   'Kaskade', 'Frontliner', 'Steve Angello', 'Sander Van Doorn', 
                   'Martin Garrix', 'Porter Robinson', 'Ferry Corsten', 'Chuckie', 
                   'Krewella', 'Coone', 'Carl Cox', 'Bobina', 'Omnia', 'Orjan Nilsen', 
                   'Zatox', 'Gareth Emery', 'Bingo Players', 'Infected Mushroom', 
                   'Eric Prydz', 'Tommy Trash', 'Wildstylez', 'Arty', 'R3hab', 'Madeon', 
                   'Vicetone', 'Brennan Heart', 'DJ Feel', 'Gunz For Hire', 'Diplo', 
                   'Tenishia', 'Noisecontrollers', 'Mike Candys', 'DJ Antoine', 
                   'Quentin Mosimann', 'Project 46', 'Blasterjaxx', 'D-Block & S-te-Fan', 
                   'Dillon Francis', 'Dannic', 'Adaro', 'Richie Hawtin', 'Martin Solveig', 
                   'Felguk', 'Myon & Shane 54', 'Cosmic Gate', 'Heatbeat', "John O'Callaghan", 
                   'Wasted Penguinz', 'Tiddey', 'Skazi', 'Da Tweekaz', 'Tenashar', 
                   'Bob Sinclar', 'Benny Benassi', 'Stafford Brothers', 'DJ BL3ND', 
                   'Paul Oakenfold', 'Mat Zo', 'Diego Miranda', 'DJs From Mars', 'Matt Darey',
                   'UMEK', 'Solarstone', 'Ummet Ozcan', 'Ran-D', 'Disclosure', 'Rudimental',
                   'Flux Pavilion', 'Nero', 'Datsik', 'Moby', 'Zeds Dead', 'The Prodigy',
                   'Bassnectar', 'Adventure Club', 'Dirty South', 'Borgore', 'Modestep', 
                   'Bonobo', 'Feed Me', 'Flosstradamus', 'The Glitch Mob', 'Rusko',
                   'Kill The Noise','Fatboy Slim', 'Zomboy', 'A-Trak', 'James Blake', 
                   'Morgan Page', 'The Bloody Beetroots', 'Quintino', 'Wolfgang Gartner', 
                   'Bakermat', 'M83', 'Pretty Lights', 'Cedric Gervais', 
                   'Sunnery James & Ryan Marciano', 'Baauer', 'Danny Avila', 'Justice', 
                   'Seven Lions', 'Royksopp', 'Bondax', 'Zero 7', 'Lemaitre', 'Noisia', 
                   'Gramatik', 'Thomas Gold', 'Basement Jaxx', 'Aphex Twin', 'Four Tet', 
                   'Flying Lotus', 'Sidney Samson', 'Paul Kalkbrenner', 'Boards Of Canada', 
                   'Maya Jane Coles', 'Groove Armada', 'Juan Magan', 'Chase & Status', 'BT', 
                   'Digitalism', 'Mount Kimbie', 'Benga', 'Audien', 'Bassjackers', 
                   'The Chainsmokers', 'DVBBS', 'Pete Tong', 'Deorro', 'DJ Snake', 
                   'Don Diablo', 'Pendulum', 'Chris Lake', 'Dzeko & Torres', 'Zhu'
        ];

        $('#dj-search .typeahead').typeahead({
          hint: true,
          highlight: true,
          minLength: 1
        },
        {
          name: 'djs',
          displayKey: 'value',
          source: substringMatcher(djs)
        });
    }); 
</script>
</head>

<body>
<form id="search_bar" class="navbar-form navbar-left">
    <div class="form-group" id="dj-search">
        <input type="text" class="form-control typeahead" placeholder="Search favourite DJs" autocomplete="off">
    </div>
</form>
</body>
</html>

如果我尝试让相同的代码用于我现有的 HTML 模板,我会不断收到错误

未捕获的类型错误:undefined 不是函数

在线

$('#dj-search .typeahead').typeahead({

什么可能导致此错误?

下面是我的完整 HTML

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>EDM Hunters | Top 100 DJs | Discover the Best of Electronic Dance Music</title>

        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="Listen to, vote on and discover the Top Electronic Dance Music Songs by the Top DJs of the world">
        <meta property="og:image" content="/static/img/edmlogo.jpg"/>

        <link rel="shortcut icon" href="/static/img/favicon.ico">
        <link href="/static/css/bootstrap.min.css" rel="stylesheet" type='text/css'/>
        <link href="/static/css/bootstrap-theme.min.css" rel="stylesheet" type='text/css'/>
        <link href="/static/css/style.css" rel="stylesheet" type='text/css'/>

        <script type="text/javascript" src="/static/js/jquery-1.9.1.js"></script>
        <script type="text/javascript" src="/static/js/bootstrap.min.js"></script>
        <script type="text/javascript" src="/static/js/typeahead.bundle.min.js"></script>
        <script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-53a4066858ab24f0"></script>

        <script type="text/javascript">
            $(document).ready(function() {
                var substringMatcher = function(strs) {
                  return function findMatches(q, cb) {
                    var matches, substringRegex;

                    // an array that will be populated with substring matches
                    matches = [];

                    // regex used to determine if a string contains the substring `q`
                    substrRegex = new RegExp(q, 'i');

                    // iterate through the pool of strings and for any string that
                    // contains the substring `q`, add it to the `matches` array
                    $.each(strs, function(i, str) {
                      if (substrRegex.test(str)) {
                        // the typeahead jQuery plugin expects suggestions to a
                        // JavaScript object, refer to typeahead docs for more info
                        matches.push({ value: str });
                      }
                    });

                    cb(matches);
                  };
                };

                var djs = ['Hardwell', 'Armin van Buuren', 'Avicii', 'Tiesto', 'David Guetta', 
                           'Dimitri Vegas & Like Mike', 'Nicky Romero', 'Steve Aoki', 'Afrojack', 
                           'Dash Berlin', 'Skrillex', 'Deadmau5', 'Alesso', 'W&W', 'Calvin Harris', 
                           'NERVO', 'Above & Beyond', 'Sebastian Ingrosso', 'Axwell', 'Aly & Fila', 
                           'Markus Schulz', 'Daft Punk', 'Headhunterz', 'Zedd', 'Knife Party', 
                           'Swedish House Mafia', 'Showtek', 'Andrew Rayel', 'Fedde Le Grand', 
                           'Dyro', 'Laidback Luke', 'Paul van Dyk', 'ATB', 'Angerfist', 'Dada Life',
                           'Kaskade', 'Frontliner', 'Steve Angello', 'Sander Van Doorn', 
                           'Martin Garrix', 'Porter Robinson', 'Ferry Corsten', 'Chuckie', 
                           'Krewella', 'Coone', 'Carl Cox', 'Bobina', 'Omnia', 'Orjan Nilsen', 
                           'Zatox', 'Gareth Emery', 'Bingo Players', 'Infected Mushroom', 
                           'Eric Prydz', 'Tommy Trash', 'Wildstylez', 'Arty', 'R3hab', 'Madeon', 
                           'Vicetone', 'Brennan Heart', 'DJ Feel', 'Gunz For Hire', 'Diplo', 
                           'Tenishia', 'Noisecontrollers', 'Mike Candys', 'DJ Antoine', 
                           'Quentin Mosimann', 'Project 46', 'Blasterjaxx', 'D-Block & S-te-Fan', 
                           'Dillon Francis', 'Dannic', 'Adaro', 'Richie Hawtin', 'Martin Solveig', 
                           'Felguk', 'Myon & Shane 54', 'Cosmic Gate', 'Heatbeat', "John O'Callaghan", 
                           'Wasted Penguinz', 'Tiddey', 'Skazi', 'Da Tweekaz', 'Tenashar', 
                           'Bob Sinclar', 'Benny Benassi', 'Stafford Brothers', 'DJ BL3ND', 
                           'Paul Oakenfold', 'Mat Zo', 'Diego Miranda', 'DJs From Mars', 'Matt Darey',
                           'UMEK', 'Solarstone', 'Ummet Ozcan', 'Ran-D', 'Disclosure', 'Rudimental',
                           'Flux Pavilion', 'Nero', 'Datsik', 'Moby', 'Zeds Dead', 'The Prodigy',
                           'Bassnectar', 'Adventure Club', 'Dirty South', 'Borgore', 'Modestep', 
                           'Bonobo', 'Feed Me', 'Flosstradamus', 'The Glitch Mob', 'Rusko',
                           'Kill The Noise','Fatboy Slim', 'Zomboy', 'A-Trak', 'James Blake', 
                           'Morgan Page', 'The Bloody Beetroots', 'Quintino', 'Wolfgang Gartner', 
                           'Bakermat', 'M83', 'Pretty Lights', 'Cedric Gervais', 
                           'Sunnery James & Ryan Marciano', 'Baauer', 'Danny Avila', 'Justice', 
                           'Seven Lions', 'Royksopp', 'Bondax', 'Zero 7', 'Lemaitre', 'Noisia', 
                           'Gramatik', 'Thomas Gold', 'Basement Jaxx', 'Aphex Twin', 'Four Tet', 
                           'Flying Lotus', 'Sidney Samson', 'Paul Kalkbrenner', 'Boards Of Canada', 
                           'Maya Jane Coles', 'Groove Armada', 'Juan Magan', 'Chase & Status', 'BT', 
                           'Digitalism', 'Mount Kimbie', 'Benga', 'Audien', 'Bassjackers', 
                           'The Chainsmokers', 'DVBBS', 'Pete Tong', 'Deorro', 'DJ Snake', 
                           'Don Diablo', 'Pendulum', 'Chris Lake', 'Dzeko & Torres', 'Zhu'
                ];

                $('#dj-search .typeahead').typeahead({
                  hint: true,
                  highlight: true,
                  minLength: 1
                },
                {
                  name: 'djs',
                  displayKey: 'value',
                  source: substringMatcher(djs)
                });
            }); 
        </script>
    </head>
    <body>
        <div id="edmhunters_body">
            <div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
                <div class="container">
                    <div class="navbar-header">
                        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                            <span class="sr-only">Toggle navigation</span>
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                        </button>
                        <a class="navbar-brand" href="#"><img id="edm" src="/static/img/edmlogo.png" alt="EDM Hunters logo"/></a>
                    </div>
                    <div class="collapse navbar-collapse">
                        <ul class="nav navbar-nav">
                            <li class="active">
                                <a href="#"><strong>Top 100 DJs</strong></a>
                            </li>
                            <li>
                                <a href="/explore/"><strong>Explore More DJs</strong></a>
                            </li>
                            <li>
                                <a href="/genres/"><strong>Browse by Genres</strong></a>
                            </li>
                            <li>
                                <a href="/monthly/"><strong>Monthly Top Songs</strong></a>
                            </li>
                            <li>
                                <a href="/trending/"><strong>Trending Songs</strong></a>
                            </li>
                        </ul>
                        <form id="search_bar" class="navbar-form navbar-left">
                            <div class="form-group" id="dj-search">
                                <input type="text" class="form-control typeahead" placeholder="Search favourite DJs" autocomplete="off">
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            <div class="container">
                <div class="jumbotron" style="color:white;background-color:#252525;">
                    <h1>EDM Hunters</h1>
                    <p>EDM Hunters is a place where you can listen to and discover the Top Electronic Dance Music Songs by the Top DJs of the world. Don't agree with a list? Vote for your favourite song. What's your #1?</p>
                    <p><a class="btn btn-primary btn-lg" role="button" href="/faq/">Learn more</a></p>
                </div>
                <div class="col-md-11">
    <div class="row dj_row">
        <div class="col-md-2 col-md-offset-1 text-center dj-md-2">
            <p><strong>#1 Hardwell</strong></p>
            <a href="/hardwell/"><img src="/static/img/1.jpg" class="img-rounded dj_img" alt="Hardwell"/></a>
        </div>
        <div class="col-md-2 text-center dj-md-2">
            <p><strong>#2 Armin van Buuren</strong></p>
            <a href="/armin-van-buuren/"><img src="/static/img/2.jpg" class="img-rounded dj_img" alt="Armin van Buuren"/></a>
        </div>
        <div class="col-md-2 text-center dj-md-2">
            <p><strong>#3 Avicii</strong></p>
            <a href="/avicii/"><img src="/static/img/3.jpg" class="img-rounded dj_img" alt="Avicii"/></a>
        </div>
        <div class="col-md-2 text-center dj-md-2">
            <p><strong>#4 Tiesto</strong></p>
            <a href="/tiesto/"><img src="/static/img/4.jpg" class="img-rounded dj_img" alt="Tiesto"/></a>
        </div>
        <div class="col-md-2 text-center dj-md-2">
            <p><strong>#5 David Guetta</strong></p>
            <a href="/david-guetta/"><img src="/static/img/5.jpg" class="img-rounded dj_img" alt="David Guetta"/></a>
        </div>
    </div>
    <div class="row dj_row">
        <div class="col-md-2 col-md-offset-1 text-center dj-md-2">
            <p><strong>#6 Dimitri Vegas &amp; Like Mike</strong></p>
            <a href="/dimitri-vegas-and-like-mike/"><img src="/static/img/6.jpg" class="img-rounded dj_img" alt="Dimitri Vegas &amp; Like Mike"/></a>
        </div>
        <div class="col-md-2 text-center dj-md-2">
            <p><strong>#7 Nicky Romero</strong></p>
            <a href="/nicky-romero/"><img src="/static/img/7.jpg" class="img-rounded dj_img" alt="Nicky Romero"/></a>
        </div>
        <div class="col-md-2 text-center dj-md-2">
            <p><strong>#8 Steve Aoki</strong></p>
            <a href="/steve-aoki/"><img src="/static/img/8.jpg" class="img-rounded dj_img" alt="Steve Aoki"/></a>
        </div>
        <div class="col-md-2 text-center dj-md-2">
            <p><strong>#9 Afrojack</strong></p>
            <a href="/afrojack/"><img src="/static/img/9.jpg" class="img-rounded dj_img" alt="Afrojack"/></a>
        </div>
        <div class="col-md-2 text-center dj-md-2">
            <p><strong>#10 Dash Berlin</strong></p>
            <a href="/dash-berlin/"><img src="/static/img/10.jpg" class="img-rounded dj_img" alt="Dash Berlin"/></a>
        </div>
    </div>
    <div class="endless_container">
        <a class="endless_more" href="/?page=2"
            rel="page">more</a>
        <div class="endless_loading" style="display: none;"><img src="/static/img/ajax-loader.gif" style="margin-left:535px;margin-top:25px;" alt="loading"/></div>
    </div>
                    <script src="/static/js/jquery-1.9.1.js"></script>
                    <script src="/static/js/endless-pagination.js"></script>
                    <script>
                        $.endlessPaginate({
                            paginateOnScroll: true,
                            paginateOnScrollMargin: 130
                        });
                    </script> 
                </div>
            </div>
            <div class="push"></div>
        </div>
        <div class="footer">
            <div id="disclaimer">
                <p>*Rankings according to <a href="http://www.djmag.com/top100?year=2013" target="_blank">DJ Mag Top 100 DJs 2013</a></p>
            </div>  
            <footer>
                <span id=copy class='pull-right'><strong>&copy; EDM Hunters 2014</strong></span>
                <a href="/contact/" id="contactus" class='pull-right'>Contact us</a>
                <a href="/faq/" id="faq" class="pull-right">FAQ</a>
                <div class="clearfix"></div>
            </footer>   
        </div>
        <script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-53a4066858ab24f0"></script>
        <script>
            (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
                (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
                m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
            })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
            ga('create', 'UA-47063606-1', 'edmhunters.com');
            ga('send', 'pageview');
        </script>
    </body>
</html>

最佳答案

正如评论中所讨论的那样:这个问题已经被原发布者解决了。 “undefined is not a function”意味着 typeahead 属性实际上是未定义的——所以它不能作为函数调用运行。通常这表示插件加载有问题,但是:

  1. typeahead 插件在 jQuery 之后加载,并且
  2. 控制台上没有错误表明插件未加载。

最后,页面中加载了另一个 jQuery 副本。所以 jQuery 在 head 中加载,然后加载 typeahead 插件(使 $('foo').typeahead() 可用)...然后是第二个副本正在加载,删除了扩展的 jQuery 函数。当 document.ready 调用触发时,使用的是第二个 jQuery,导致错误。

关于javascript - 未捕获的类型错误 : undefined is not a function - typeahead. js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24403635/

有关javascript - 未捕获的类型错误 : undefined is not a function - typeahead. js的更多相关文章

  1. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  2. ruby - Infinity 和 NaN 的类型是什么? - 2

    我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串

  3. ruby - 检查方法参数的类型 - 2

    我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)

  4. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  5. ruby-on-rails - 如何在 Rails View 上显示错误消息? - 2

    我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c

  6. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  7. ruby-on-rails - 错误 : Error installing pg: ERROR: Failed to build gem native extension - 2

    我克隆了一个rails仓库,我现在正尝试捆绑安装背景:OSXElCapitanruby2.2.3p173(2015-08-18修订版51636)[x86_64-darwin15]rails-v在您的Gemfile中列出的或native可用的任何gem源中找不到gem'pg(>=0)ruby​​'。运行bundleinstall以安装缺少的gem。bundleinstallFetchinggemmetadatafromhttps://rubygems.org/............Fetchingversionmetadatafromhttps://rubygems.org/...Fe

  8. ruby - #之间? Cooper 的 *Beginning Ruby* 中的错误或异常 - 2

    在Cooper的书BeginningRuby中,第166页有一个我无法重现的示例。classSongincludeComparableattr_accessor:lengthdef(other)@lengthother.lengthenddefinitialize(song_name,length)@song_name=song_name@length=lengthendenda=Song.new('Rockaroundtheclock',143)b=Song.new('BohemianRhapsody',544)c=Song.new('MinuteWaltz',60)a.betwee

  9. ruby-on-rails - 每次我尝试部署时,我都会得到 - (gcloud.preview.app.deploy) 错误响应 : [4] DEADLINE_EXCEEDED - 2

    我是Google云的新手,我正在尝试对其进行首次部署。我的第一个部署是RubyonRails项目。我基本上是在关注thisguideinthegoogleclouddocumentation.唯一的区别是我使用的是我自己的项目,而不是他们提供的“helloworld”项目。这是我的app.yaml文件runtime:customvm:trueentrypoint:bundleexecrackup-p8080-Eproductionconfig.ruresources:cpu:0.5memory_gb:1.3disk_size_gb:10当我转到我的项目目录并运行gcloudprevie

  10. ruby - Ruby 有 `Pair` 数据类型吗? - 2

    有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳

随机推荐