如何提取它们&&如何删除它们

时间:2019-02-08 19:34:24

标签: javascript arrays string

我的两个问题仍然存在于数组上(我是菜鸟,我正在尝试学习,对不起)。所以...

// Prob_1 我只想从每次测试中提取所需的信息。我在不使用对象的情况下这样做。

//问题2 我正在尝试删除所有废纸characters字符,以将其他废纸characters字符存储在新的var中,以显示消息

P.S:我只是在尝试一些东西,看看怎么做

//Pob_1

const hell = ['test1: Oh god', 'test2: Plz god', 'test3: Plz god no'];

let extractedChar = [];

extractedChar = (databaseEntry[1].Name + databaseEntry[2].Rank + databaseEntry[0].Faction);

console.log(extractedChar);

//Prob_2

const heavenAndHell = [['☆','S','a','☆','☆','t'],
                       ['a','☆','n','☆','H','e'],
                       ['l','p','☆','s','☆','y'],
                       ['o','☆','u','x','☆','D']];

function losingIt(){
  for (let i = 0; i < heavenAndHell ; i++){
    for (let x = 0; x < heavenAndHell [i].length; x++){

      var heaven = '☆';

      if (heaven = '☆'){
        return false;
      } else {
        return true;
      }
    } 
  }
}

2 个答案:

答案 0 :(得分:0)

问题1:

const hell = ['test1: Oh god', 'test2: Plz god', 'test3: Plz god no'];

/* with reduce */

const res = hell.reduce((all, curr) => {
  const obj = curr.split(":");
  all.push({
    [obj[0]]: obj[1]
  });
  return all;
}, [])

/* with map */

const res2 = hell.map(el => ({
  [el.split(":")[0]]: el.split(":")[1]
}))

console.log(res2);

问题2:

const heavenAndHell = [
  ['☆', 'S', 'a', '☆', '☆', 't'],
  ['a', '☆', 'n', '☆', 'H', 'e'],
  ['l', 'p', '☆', 's', '☆', 'y'],
  ['o', '☆', 'u', 'x', '☆', 'D']
];

/* first solution*/

var word = "";

heavenAndHell.map(el => {
  el.map(el => {
    if (el.match(/[a-z_A-Z]/i))
      word += el;
  })
})

console.log(word);

/* seconde solution */
const res = heavenAndHell.flat().filter((el) => el.match(/[a-z_A-Z]/i)).join("");

console.log(res);

答案 1 :(得分:0)

问题1-map使用split删除不需要的字符:

const hell = ['test1: Oh god', 'test2: Plz god', 'test3: Plz god no'];

const words = hell.map(s => s.split(": ")[1]);

console.log(words);


问题2-再次map遍历数组中不需要的字符,但改用正则表达式对其进行测试,然后执行一些数组操作以删除空数组元素并删除多维数组:

const heavenAndHell = [
  ['☆', 'S', 'a', '☆', '☆', 't'],
  ['a', '☆', 'n', '☆', 'H', 'e'],
  ['l', 'p', '☆', 's', '☆', 'y'],
  ['o', '☆', 'u', 'x', '☆', 'D']
];

const words = heavenAndHell.map(a => a.map(e => e.match(/[A-Za-z]/))).flat(2).filter(Boolean).join("");

console.log(words);

相关问题