Javascript剥离数组值的一部分并创建新数组

时间:2017-01-23 09:49:11

标签: javascript arrays

我有一个如下所示的数组:

["text1[483]", "text 2[411]", "text 3[560]", "text[484]"]

我需要做的是从这个数组的值创建关于我需要创建2个新数组。

一个数组将包含文本和[],其中的任何内容都应该从中消失。

另一个数组只包含没有[]

的数字

因此,新数组看起来像这样:

TextArray:

["text1", "text 2", "text 3", "text"]

NumberArray:

["483", "411", "560", "484"]

我该怎么做?

3 个答案:

答案 0 :(得分:1)

var initialArray = ["text1[483]", "text 2[411]", "text 3[560]", "text[484]"];
    
var texts = initialArray.map(function(v){  return v.split('[')[0]} );

console.log(texts);
// ["text1", "text 2", "text 3", "text"]
    
var numbers = initialArray.map(function(v){  return +v.match(/\[(\d+)\]/)[1]} );

console.log(numbers);
// [483, 411, 560, 484]

答案 1 :(得分:0)

您可以根据[拆分并删除字符串]的最后一个字符



var arr = ["text1[483]", "text 2[411]", "text 3[560]", "text[484]"];

var firstArray = [];
var secondArray = [];

arr.forEach(function(item) {
  var split = item.split("[");
  firstArray.push(split[0]);
  secondArray.push(split[1].slice(0,-1));
});

console.log(JSON.stringify(firstArray));
console.log(JSON.stringify(secondArray));




答案 2 :(得分:0)

您可以使用正则表达式并分隔想要的部分。

var array = ["text1[483]", "text 2[411]", "text 3[560]", "text[484]"],
    texts = [],
    numbers = [];

array.forEach(function (a) {
    var m = a.match(/^(.*)\[(.*)\]$/);
    texts.push(m[1]);
    numbers.push(m[2]);    
});

console.log(texts);
console.log(numbers);
.as-console-wrapper { max-height: 100% !important; top: 0; }