简体   繁体   English

如何从数组元素中删除“:”

[英]How can I remove ":" from the elements of array

I am Trying to convert the array [ '9:00', '9:40', '9:50', '11:00', '15:00', '18:00' ] to [ '900', '940', '950', '1100', '1500', '1800' ] in javascript.我正在尝试将数组 ['9:00', '9:40', '9:50', '11:00', '15:00', '18:00'] 转换为 ['900', '940'、'950'、'1100'、'1500'、'1800'] 在 javascript 中。

You can do it in this way:-你可以这样做: -

let oldArray = ['9:00', '9:40', '9:50', '11:00', '15:00', '18:00'];
let newArray = oldArray.map(elem => elem.replace(':',''));
console.log(newArray);

What you're looking for is the .map() function.您正在寻找的是.map() function。 This function iterates over all items in the array, allowing you to execute code on said iterations.这个 function 迭代数组中的所有项目,允许您在所述迭代上执行代码。 Use what I've provided below.使用我在下面提供的内容。

const arrayOfTimestamps = [ '9:00', '9:40', '9:50', '11:00', '15:00', '18:00' ];

const formattedTimestamps = arrayOfTimestamps.map(time => time.replace(/:/g, ''))

As an explanation, .map() iterates over each item, and the time is being handled by regex.作为解释, .map()迭代每个项目,时间由正则表达式处理。 the /g aka global flag tells the regex to remove all semicolors's from the strings. /g又名全局标志告诉正则表达式从字符串中删除所有半色。

For more information on how .map() works, here.有关.map()如何工作的更多信息,请点击此处。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

var list = [ '9:00', '9:40', '9:50', '11:00', '15:00', '18:00' ];

for (var i = 0; i < list.length; i++)
{
  list[i] = list[i].replace(':', ''); 
}

First, you need a regular expression for this similar to this one:首先,您需要一个类似于此的正则表达式:

var regExpStuff = /[/:]/;
var array = removeItem(unique, regExpStuff);

Then you need a remove function with splice method and using the regex above:然后您需要使用拼接方法并使用上面的正则表达式删除 function :

function removeItem(originalArray, itemToRemove) {
    var j = 0;
    while (j < originalArray.length) {
        if (originalArray[j] == itemToRemove) {
            originalArray.splice(j, 1);
    } else { j++; }
}
return originalArray;
}

Use map to apply a callback to each element of the array, and return the processed result.使用map对数组的每个元素应用回调,并返回处理后的结果。

let arr = ['9:00', '9:40', '9:50', '11:00', '15:00', '18:00']
arr = arr.map(v => v.replace(/:/g, '')

Flag g for Regex will replace all : occurrences. Regex 的标志g将替换所有:出现。 Without it only the first : will be removed.没有它,只有第一个:将被删除。

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

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