记录字段中的模式计数和创建数组
Counting patterns in record fields and creating array
如何计算记录字段中的模式并创建它的数组?
例如:在中搜索(使用下面的例子)目前给了我多个
的输出0 0 (**in** seen at index 0 of book 0 title record)
0 13 (**in** seen at index 13 of book 0 title record)
1 19 (**in** seen at index 0 of book 1 title record)
2 -1 (**in** not seen at any index of title record)
理想情况下,我希望代码返回:
2,1,0 (**in** seen 2 times in book 0 title record, **in** seen 1 time in
book 1 title record and **in** not seen in book 2 title record
提前感谢!
books = [
{
title: "Inheritance: Inheritance Cycle, Book 4",
author: "Christopher Paolini",
},
{
title: "The Sense of an Ending",
author: "Julian Barnes"},
{
title: "Snuff Discworld Novel 39",
author: "Sir Terry Pratchett",
}
]
search = prompt("Title?");
function count(books, pattern) {
if (pattern) {
var num = 0;
var result = [];
for (i = 0; i < books.length; i++) {
var index = books[i].title.toLowerCase().indexOf(pattern.toLowerCase());
do {
alert(i + " " + index);
index = books[i].title.toLowerCase().indexOf(pattern.toLowerCase(), index + 1);
}
while (index >= 0)
num = 0;
}
return result;
}
else {
return ("Nothing entered!");
}
}
alert(count(books, search));
使用String.prototype。Match ,它返回一个匹配数组(如果没有则返回null),数组的长度告诉您有多少个匹配。例如
var books = [
{
title: "Inheritance: Inheritance Cycle, Book 4",
author: "Christopher Paolini",
},
{
title: "The Sense of an Ending",
author: "Julian Barnes"},
{
title: "Snuff Discworld Novel 39",
author: "Sir Terry Pratchett",
}
];
var result = [];
var re = /in/ig;
var matches;
for (var i=0, iLen=books.length; i<iLen; i++) {
matches = books[i].title.match(re);
result.push(matches? matches.length : 0);
}
alert(result);
相关文章:
- knex:根据结果创建数组的合适方法是什么
- 在javascript中创建数组,而不是if.else
- 使用来自不同循环Javascript的数据创建数组
- 尝试从计算创建数组时数组长度无效
- 循环选择标记并创建数组或字符串
- 根据 Array Javascript 中的字符串值动态创建数组名称
- 通过动态创建数组名称在单击函数中引用 javascript 数组
- 如何在不完成添加序列的情况下从rxjs创建数组
- 如何在不创建数组的情况下使用NgFor来生成矩阵UI模式
- 使用jquery从TextArea创建数组
- jquery动态创建数组
- 从现有数组创建数组
- 使用对象的副本创建数组(Javascript)
- 基于分隔符/方括号的实例创建数组
- 如何创建数组取决于是否在jQuery中设置了变量
- 使用JavaScript's Reduce从对象数组创建数组
- 在 JavaScript 中动态创建数组
- 在 javascript 中使 split() 方法使用双引号而不是单引号创建数组
- 在 $.each 函数中使用条件来创建数组
- 如何修改此代码,以便创建数组并将事件添加到数组中