search

Home  >  Q&A  >  body text

javascript - Ask a question about array sort method

This example is an example I saw online:

<script type="text/javascript">
            var objectList2 = new Array();

            function WorkMate(name, age) {
                this.name = name;
                var _age = age;
                this.age = function() {       //我实在是没有看懂这里为什么要添加这样一个方法
                    if(!arguments) {          //如果没有实参传入
                        _age = arguments[0];  //那_age的值为实参的第一个的值   **没有实参传入,哪来的第一个值?**
                    } else {
                        return _age;
                    }
                }

            }
            objectList2.push(new WorkMate('jack', 20));
            objectList2.push(new WorkMate('tony', 25));
            objectList2.push(new WorkMate('stone', 26));
            objectList2.push(new WorkMate('mandy', 23));
            //按年龄从小到大排序
            objectList2.sort(function(a, b) {
                return a.age() - b.age();
            });
            for(var i = 0; i < objectList2.length; i++) {
                document.writeln('<br />age:' + objectList2[i].age() + ' name:' + objectList2[i].name);
            }
        </script>

I don’t know if I understand this paragraph correctly. Could you please help me take a look at it? How do I understand the arguments in the middle? What is the use of this method? Thanks

PHP中文网PHP中文网2752 days ago440

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-05-19 10:18:03

    function a(){
        console.log(!arguments);
    }
    a()//false
    a(1)//false

    That if judgment seems useless...arguments are necessary for functions, regardless of whether you pass in parameters or not.

    reply
    0
  • Cancelreply