[英]How to slice an array to get only the last 2 numbers in that array - JavaScript
我是 javascript 的新手。 請幫我解決這個問題。
如何對數組進行切片以僅獲取該數組中的最后 2 個數字 - JavaScript,如下所示:[1234, 5432, 765764, 546542, 234, 5454] 到 [34, 32, 64, 42, 34, 54]
謝謝!
您可以使用map()方法。
const array = [1234, 5432, 765764, 546542, 234, 5454]; const arrayMap = array.map(x => x % 100); console.log(arrayMap);
好吧,您可以在這里使用模數來查找每個輸入數字的最后兩位數字:
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);
在 javascript 中切片將獲得原始數組的子數組,您正在尋找的是值的轉換。
您需要的操作是取數字並應用% 100
。 這將返回除以 100 時的余數,即最后兩位數。
在代碼中,這看起來像:
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.