nunnly / everycode

Javascript 每日一练
116 stars 26 forks source link

2015年4月3日,数据模拟 #45

Open VaJoy opened 9 years ago

VaJoy commented 9 years ago

清明放假了,俺也来贡献一道题目吧。 有时候吧,咱会自己写份JSON文件来模拟服务端响应的数据。 假设你在给一个阅读app做一项“换一批书”的功能,它会随机返回一串既有书籍数据中的n项(这个n是可定义范围的):

    var books = [{"name":"高级程序设计","version":"2","cover":"1.jpg"},
        {"name":"高级程序设计","version":"3","cover":"2.jpg"},
        {"name":"霸道总裁","version":"1","cover":"3.jpg"},
        {"name":"烹饪大全","version":"1","cover":"4.jpg"},
        {"name":"乔布斯自传","version":"2","cover":"5.jpg"},
        {"name":"时间简史","version":"2","cover":"6.jpg"},
        {"name":"辞海","version":"3","cover":"7.jpg"},
        {"name":"简爱","version":"2","cover":"8.jpg"}];

    function pickSome(books,min,max){
        //TODO:随机返回[min,max]本书
    }

    console.log(pickSome(books,2,4));//随机返回2本或3本或4本书,结果可能如下:
    //[{"name":"高级程序设计","version":"3","cover":"2.jpg"},
    // {"name":"乔布斯自传","version":"2","cover":"5.jpg"},
    // {"name":"时间简史","version":"2","cover":"6.jpg"},
    // {"name":"霸道总裁","version":"1","cover":"3.jpg"}]

噢亲爱的请注意下,咱全部书籍数据里可能有多本同名的书呢(比如“高级程序设计”),咱不太希望用户换到的数据里有两本名字一样的书(即使它们版本不一样),所以这里也要处理下哦。