猿问

一道js类的面试题,没整明白要做什么?求答案

请写一段js程序,定义一个列表类List,该类包括两个成员:属性length(表示列表中的元素个数)和方法add(向列表添加元素),其中要求构造函数和add方法的参数为动态参数。

冉冉说
浏览 1160回答 2
2回答

拉风的咖菲猫

使用ES5 构造函数仿写上面的答案function List1(){ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.items = [];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(var i =0; i<arguments.length;i++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.items.push(arguments[i]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.length = arguments.length;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.add = function(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(var i =0; i<arguments.length;i++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.items.push(arguments[i]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.length = this.items.length;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }

慕标5832272

class List{&nbsp; &nbsp; constructor(...items){&nbsp; &nbsp; &nbsp; &nbsp; this.items = items&nbsp; &nbsp; &nbsp; &nbsp; this.length = items.length&nbsp; &nbsp; }&nbsp; &nbsp; add(...items) {&nbsp; &nbsp; &nbsp; &nbsp; this.items.push(...items)&nbsp; &nbsp; &nbsp; &nbsp; this.length = items.length&nbsp; &nbsp; }}
随时随地看视频慕课网APP
我要回答