Javascript 根据空格拆分字符串,并以angular2读取
我正在angular2中创建一个管道,在这里我想在空白处分割字符串,然后将其作为数组读取Javascript 根据空格拆分字符串,并以angular2读取,javascript,angular2-pipe,Javascript,Angular2 Pipe,我正在angular2中创建一个管道,在这里我想在空白处分割字符串,然后将其作为数组读取 let stringToSplit = "abc def ghi"; StringToSplit.split(" "); console.log(stringToSplit[0]); 当我记录这个时,我总是得到“a”作为输出。哪里出了问题?做了一些更改: 让stringToSplit=“abc def ghi”; 设x=stringToSplit.split(“”); console.log(x[0])
let stringToSplit = "abc def ghi";
StringToSplit.split(" ");
console.log(stringToSplit[0]);
当我记录这个时,我总是得到“a”作为输出。哪里出了问题?做了一些更改:
让stringToSplit=“abc def ghi”;
设x=stringToSplit.split(“”);
console.log(x[0])代码>
该方法返回一个数组。您将获得原始字符串的第一个元素,而不是使用其结果
let stringToSplit = "abc def ghi";
StringToSplit.split(" ");
console.log(stringToSplit[0]);
首先,stringToSplit
和stringToSplit
是不同的。JS区分大小写。另外,您不会将StringToSplit.split(“”)的结果保存到任何位置,然后只输出字符串StringToSplit
的第一个字符,即a
。你可以这样做:
让stringToSplit=“abc def ghi”;
console.log(stringToSplit.split(“”[0]);//stringToSplit.split(“”)返回数组,然后我们使用[0]获取数组的第一个元素。
我为它创建了这个npm包:
精彩的。很高兴为您提供帮助。如果答案解决了您的问题,请随时将其标记为已完成。谢谢@RaduCojocariThank@Radu Cojocari,split()函数返回了一个数组。我希望你能理解为什么现在总是得到“a”。它不是给同一个字符串赋值。如果它也可以的话,这就像在string中指定string[],这是一个更清晰的答案。至少你解释了哪里出了问题。
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;
}