如何使用 JavaScript 轻松截断数组? [英] How to easily truncate an array with JavaScript?

查看:20
本文介绍了如何使用 JavaScript 轻松截断数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Linq 有一个方便的操作符方法,称为 Take(),可以在任何实现 IEnumerable 的东西中返回给定数量的元素.jQuery 中是否有类似的用于处理数组的东西?

Linq has a convenient operator method called Take() to return a given number of elements in anything that implements IEnumerable. Is there anything similar in jQuery for working with arrays?

或者,换个方式问:如何在 Javascript 中截断数组?

Or, asked differently: how can I truncate an array in Javascript?

推荐答案

有一个 切片 方法

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
arr = arr.slice(0, 4);
console.log(arr);

将返回前四个元素.

如果您想丢弃其他值,请不要忘记将其分配回您的变量.

Don't forget to assign it back to your variable if you want to discard the other values.

注意:这只是普通的javascript,不需要jquery.

Note: This is just regular javascript, no need for jquery.

这篇关于如何使用 JavaScript 轻松截断数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆