简体   繁体   English

javascript 数组。将连续的 srings 值加入新数组

[英]javascript array.Join continious srings values into new array

i have this array = ["john", "mike", "george", 55, "hello", 344, "goodmorning"] and i want to take this:["johnmikegeorge",55,"hello",344,"goodmorning"].I want where there are continuous strings to unite them into one.我有这个数组 = ["john", "mike", "george", 55, "hello", 344, "goodmorning"] 我想拿这个:["johnmikegeorge",55,"hello",344, “早安”]。我想在有连续字符串的地方将它们合并为一个。

  var s = ""
    var new_data = []
    var pin = ["john", "mike", "george", 55, "hello", 344, "goodmorning"]
    for (let i = 0; i < pin.length; i++) {
      if (typeof pin[i] === "string") {
        s = s + pin[i]
        new_data.push(s)
      } else {
        s = ""
        new_data.push(pin[i])
      }
    }
    console.log(new_data)

In previous code i take this ["john", "johnmike", "johnmikegeorge", 55, "hello", 344, "goodmorning"]在之前的代码中,我采用了这个 ["john", "johnmike", "johnmikegeorge", 55, "hello", 344, "goodmorning"]

You could check the value and last item of the result set, if they are strings and add the actual string as well.您可以检查结果集的值和最后一项(如果它们是字符串)并添加实际字符串。

Otherwise push the item.否则推项目。 This is either a starting string of a series or a number.这是一个系列的起始字符串或一个数字。

 var array = ["john", "mike", "george", 55, "hello", 344, "goodmorning"], result = array.reduce((r, v) => { if (typeof v === 'string' && typeof r[r.length - 1] === 'string') { r[r.length - 1] += v; } else { r.push(v); } return r; }, []); console.log(result);

I've modified what you already have to make it work.我已经修改了你已经必须让它工作的东西。 whenever you get a number, you push the concatenated string that you found before that number and then push the number.每当您获得一个数字时,您都会推送您在该数字之前找到的连接字符串,然后推送该数字。 the if condition after the for loop is to check if you have more strings after the last number is pushed. for 循环后的 if 条件是检查在推入最后一个数字后是否还有更多字符串。

var s = "";
var new_data = []
var pin = ["john", "mike", "george", 55, "hello", 344, "goodmorning"]

for (let i = 0; i < pin.length; i++) {
  if (typeof pin[i] === "string") {
    s = s + pin[i]
  } else {
    if (s !== "") {
      new_data.push(s);
      s = "";
    }
    new_data.push(pin[i])
  }
}
if (s !== "") {
  new_data.push(s);
}

console.log(new_data)

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

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