[英]How to loop through an array and put the result to an array using react and javascript?
i have an array like so,我有一个这样的数组,
const array = ["item1/1", "item2/3", "item3/4"]
now i want to loop through these array elements one by one and get only the values from the strings ie, from first array element "item1/1" should get 1 and put it to an output array similarly for array element 2 "item2/3" should get 3 and put it to output array.现在我想逐个循环遍历这些数组元素并仅从字符串中获取值,即,从第一个数组元素“item1/1”应该得到 1 并将其放入 output 数组,类似地用于数组元素 2“item2/3 " 应该得到 3 并将其放入 output 阵列。 similarly for array element "item3/4" should get 4 and put it to output array.同样对于数组元素“item3/4”应该得到 4 并将其放入 output 数组。
so the expected output array should be ["1", "3", "4"]所以预期的 output 数组应该是 ["1", "3", "4"]
i have tried below,我在下面尝试过,
const find = React.useMemo(() => {
if (arr.length >= 0) {
const match = arr[0].match(/([\w-]+)\/([^/]+)\/$/);
if (match) return [match[2]];
}
}, [arr])
but above code does for one array element.但上面的代码适用于一个数组元素。 how can i loop through array and push the return match in an output array.我如何遍历数组并将返回匹配推送到 output 数组中。
i am new to programming.我是编程新手。 could someone help me with this.有人可以帮我解决这个问题。 thanks.谢谢。
You can iterate over your array by map method, and on every itration split your string by /
character, then just returining the secion after /
.您可以通过map方法迭代您的数组,并在每次迭代时按/
字符拆分您的字符串,然后在/
之后返回部分。 like this:像这样:
const array = ["item1/1", "item2/3", "item3/4"] const result = array.map(str => str.split('/').pop()) console.log(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.