gpt4 book ai didi

javascript - JS : how to get FIrst N elements of associative array

转载 作者:行者123 更新时间:2023-11-29 21:48:59 25 4
gpt4 key购买 nike

我有那个 J 结构:

var rooms={};
rooms["room1"] = 10;
rooms["room2"] = 25;
rooms["room3"] = 15;
rooms["room4"] = 1;
rooms["room5"] = 10;
rooms["room6"] = 181;
rooms["somrthing"] = value;

我正在尝试编写一个函数来检索前 N 个元素

例如:

function getElements(limit) {
..
}

如果 limit = 3 将返回一个像这样的对象:

Object 
{room1: 10, room2: 25, room3: 15}

(前 3 个元素:我不需要订购!)

最佳答案

function getTopElements(limit) {
var newRooms = {};
var i = 0;
for(r in rooms) {
if(i < limit) {
newRooms[r] = rooms[r];
i++;
}
else
return newRooms;
}
return newRooms;
}

jsfiddle DEMO

关于javascript - JS : how to get FIrst N elements of associative array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30132523/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com