Javascript 根据空格拆分字符串并在 angular2 中读取

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44900110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:46:53  来源:igfitidea点击:

Split string based on spaces and read that in angular2

javascriptangular2-pipe

提问by Abhinav Mishra

I am creating a pipe in angular2 where I want to split the string on white spaces and later on read it as an array.

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

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

When I log this, I always get "a" as output. Where I am going wrong?

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

回答by Radu Cojocari

Made a few changes:

做了一些改动:

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

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

The split method returns an array. Instead of using its result, you are getting the first element of the original string.

分割方法返回一个数组。您不是使用其结果,而是获取原始字符串的第一个元素。

回答by curveball

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

First, stringToSplitand StringToSplitare not the same. JS is case sensitive. Also you dont save result of StringToSplit.split(" ")anywhere and then you just output the first character of the string stringToSplitwhich is a. You could do like this:

第一,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]

PS. also it is more about JavaScript than TypeScript or Angular.

附注。与 TypeScript 或 Angular 相比,它更多地是关于 JavaScript 的。