简体   繁体   English

如何对数组进行切片以仅获取该数组中的最后 2 个数字 - JavaScript

[英]How to slice an array to get only the last 2 numbers in that array - JavaScript

i'm a newbie in javascript.我是 javascript 的新手。 Please help me to solve this problem.请帮我解决这个问题。

How to slice an array to get only the last 2 numbers in that array - JavaScript, like this: [1234, 5432, 765764, 546542, 234, 5454] to [34, 32, 64, 42, 34, 54]如何对数组进行切片以仅获取该数组中的最后 2 个数字 - JavaScript,如下所示:[1234, 5432, 765764, 546542, 234, 5454] 到 [34, 32, 64, 42, 34, 54]

Thank you!谢谢!

You can use the map() method.您可以使用map()方法。

 const array = [1234, 5432, 765764, 546542, 234, 5454]; const arrayMap = array.map(x => x % 100); console.log(arrayMap);

Well you could just use the modulus here to find the last two digits of each input number:好吧,您可以在这里使用模数来查找每个输入数字的最后两位数字:

 var input = [1234, 5432, 765764, 546542, 234, 5454]; var output = []; for (var i=0; i < input.length; ++i) { output.push(input[i] % 100); } console.log(output);

Slicing in javascript would be to get a sub array of the original array, what you're looking for is a transformation of the values.在 javascript 中切片将获得原始数组的子数组,您正在寻找的是值的转换。

The operation you need is to take the number and apply % 100 .您需要的操作是取数字并应用% 100 This will return the remainder from when dividing with 100, which becomes the last two digits.这将返回除以 100 时的余数,即最后两位数。

In code this will look like:在代码中,这看起来像:

list = [11234, 5432, 765764, 546542, 234, 5454]
newList = list.map( (num) => { return num % 100 })
console.log(newList)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM