我在数组中有10个对象,如下所示:
let arr = [{"id":1, "name": "abc"},{"id":2, "name": "fsd"},{"id":3, "name": "fasd"},{"id":4, "name": "fsdfas"},{"id":5, "name": "fad"},{"id":6, "name": "fasdf"},{"id":7, "name": "fasd"},{"id":8, "name": "fasdf"},{"id":9, "name": "fasdfs"},{"id":10, "name": "abc"}]
我的查询:我想只循环数组中的前5个对象并打破循环。 任何帮助将不胜感激。
答案 0 :(得分:3)
let arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
for (let i = 0; i < 5; i++) {
console.log(arr[i]);
}
看起来您正在使用ES2015 +,因此请注意for循环约束中的let i
。这避免了i
变量泄漏到外部范围的值。
答案 1 :(得分:2)
旧学校:
let arr = [{"id":1, "name": "abc"},{"id":2, "name": "fsd"},{"id":3, "name": "fasd"},{"id":4, "name": "fsdfas"},{"id":5, "name": "fad"},{"id":6, "name": "fasdf"},{"id":7, "name": "fasd"},{"id":8, "name": "fasdf"},{"id":9, "name": "fasdfs"},{"id":10, "name": "abc"}]
// Math.min (just in case arr.length < 5)
for (let i = 0; i < Math.min(5, arr.length); i++) {
console.log(arr[i]);
}
答案 2 :(得分:0)
你可以试试这个。
let arr = [{"id":1, "name": "abc"},{"id":2, "name": "fsd"},{"id":3, "name": "fasd"},{"id":4, "name": "fsdfas"},{"id":5, "name": "fad"},{"id":6, "name": "fasdf"},{"id":7, "name": "fasd"},{"id":8, "name": "fasdf"},{"id":9, "name": "fasdfs"},{"id":10, "name": "abc"}]
arr.slice(0, 5).forEach( item => console.log(item));