【问题标题】:Split string based on spaces and read that in angular2根据空格拆分字符串并在 angular2 中读取
【发布时间】:2017-12-07 13:56:09
【问题描述】:

我正在 angular2 中创建一个管道,我想在空格上拆分字符串,然后将其作为数组读取。

let stringToSplit = "abc def ghi";
StringToSplit.split(" ");
console.log(stringToSplit[0]);

当我记录这个时,我总是得到“a”作为输出。我哪里出错了?

【问题讨论】:

  • 我希望你明白为什么你现在总是得到“a”。
  • 它没有为相同的字符串赋值。如果它也可以,它就像在 string 中分配 string[]

标签: javascript angular2-pipe


【解决方案1】:

做了一些改动:

let stringToSplit = "abc def ghi"; let x = stringToSplit.split(" "); console.log(x[0]);

split 方法返回一个数组。你得到的是原始字符串的第一个元素,而不是使用它的结果。

【讨论】:

  • 太棒了。很高兴为您提供帮助。
  • 如果它解决了您的问题,请随时将答案标记为已完成。它也会帮助其他人。
  • 谢谢@RaduCojocari
  • 感谢@Radu Cojocari,split() 函数返回一个数组
【解决方案2】:
let stringToSplit = "abc def ghi";
StringToSplit.split(" ");
console.log(stringToSplit[0]);

首先,stringToSplitStringToSplit 不一样。 JS 区分大小写。此外,您不会将StringToSplit.split(" ") 的结果保存在任何地方,然后您只需输出字符串stringToSplit 的第一个字符a。你可以这样做:

    let stringToSplit = "abc def ghi";
    console.log(stringToSplit.split(" ")[0]); // stringToSplit.split(" ") returns array and then we take the first element of the array with [0]

附言。此外,它更多地是关于 JavaScript,而不是 TypeScript 或 Angular。

【讨论】:

  • 这是一个更清晰的答案。至少你解释了哪里出了问题。
【解决方案3】:

我为它创建了这个 npm 包:https://www.npmjs.com/package/search-string-eerg

    function customSearch(s, p) {
      let x = p.split(" ");
        var find = true;
        for (var partIndex in x) {
    if (s.toLowerCase().indexOf(x[partIndex]) > -1) {
      // Let this item feature in the result set only if other parts of the
      // query have been found too
      find = find && true;
    } else {
      // Even if a single part of the query was not found, this item
      // should not feature in the results
      find = false;
    }
     }
     return find;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 2014-02-11
    • 2017-06-18
    • 2015-11-26
    相关资源
    最近更新 更多