javascript - Ask a question about array sort method
PHP中文网
PHP中文网 2017-05-19 10:16:03
0
1
436

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中文网

认证高级PHP讲师

reply all(1)
Ty80
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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template