作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 JS 对象。我只尝试使用前 5 个值
console.log(Object.keys(uniqVisitorDeviceType),Object.values(uniqVisitorDeviceType));
我得到了
(27) ["iPhone", "Windows NT 6.1", "Windows NT 10.0", "Macintosh", "iPad", "Windows NT 6.2", "Windows NT 6.3", "X11", "compatible", "Windows NT 5.1", "Linux", "Windows", "TweetmemeBot/4.0", ") { :", "Windows NT 6.0", "User-Agent,Mozilla/5.0 ", "KHTML, like Gecko", "Unknown", "Android", "Android 7.1.1", "Android 7.1.2", "Windows NT x.y", "Windows NT 6.1) AppleWebKit/537.36 ", "Windows NT 5.0", "Windows NT 8.0", "web crawler :: robots.txt exclude elefent", "Windows NT"]
(27) [198, 2197, 2381, 1271, 11, 46, 81, 417, 1752, 87, 225, 70, 8, 14, 6, 1, 6, 9, 1, 1, 2, 2, 7, 1, 1, 1, 1]
如何获取 5 值顺序?命令 ?
-2381
-2197
-1752
-1271
-417
-225
-198
....
console.log(JSON.stringify(uniqVisitorDeviceType));
让出这个
{"iPhone":198,"Windows NT 6.1":2198,"Windows NT 10.0":2381,"Macintosh":1271,"iPad":11,"Windows NT 6.2":46,"Windows NT 6.3":81,"X11":417,"compatible":1752,"Windows NT 5.1":87,"Linux":225,"Windows":70,"TweetmemeBot/4.0":8,") { :":14,"Windows NT 6.0":6,"User-Agent,Mozilla/5.0 ":1,"KHTML, like Gecko":6,"Unknown":9,"Android":1,"Android 7.1.1":1,"Android 7.1.2":2,"Windows NT x.y":2,"Windows NT 6.1) AppleWebKit/537.36 ":7,"Windows NT 5.0":1,"Windows NT 8.0":1,"web crawler :: robots.txt exclude elefent":1,"Windows NT":1}
最佳答案
您可以使用sort()
来制作对象值的有序列表。然后使用 slice(0,n)
获取顶部的 n
元素。
let obj = {"iPhone":198,"Windows NT 6.1":2198,"Windows NT 10.0":2381,"Macintosh":1271,"iPad":11,"Windows NT 6.2":46,"Windows NT 6.3":81,"X11":417,"compatible":1752,"Windows NT 5.1":87,"Linux":225,"Windows":70,"TweetmemeBot/4.0":8,") { :":14,"Windows NT 6.0":6,"User-Agent,Mozilla/5.0 ":1,"KHTML, like Gecko":6,"Unknown":9,"Android":1,"Android 7.1.1":1,"Android 7.1.2":2,"Windows NT x.y":2,"Windows NT 6.1) AppleWebKit/537.36 ":7,"Windows NT 5.0":1,"Windows NT 8.0":1,"web crawler :: robots.txt exclude elefent":1,"Windows NT":1}
let res = Object.values(obj).sort((a,b) => b-a).slice(0,5);
console.log(res)
关于javascript - 如何从 JS 对象获取前 5 个属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55711035/
我是一名优秀的程序员,十分优秀!