我正在编写一个脚本来计算字符串中出现某个字符串(在本例中为坐标)的次数。我目前有以下内容:
if (game_data.mode == "incomings") {
var table = document.getElementById("incomings_table");
var rows = table.getElementsByTagName("tr");
var headers = rows[0].getElementsByTagName("th");
var allcoord = new Array(rows.length);
for (i = 1; i < rows.length - 1; i++) {
cells = rows[i].getElementsByTagName("td");
var contents = (cells[1].textContent);
contents = contents.split(/\(/);
contents = contents[contents.length - 1].split(/\)/)[0];
allcoord[i - 1] = contents
}}
所以现在我有我的变量allcoords。如果我提醒它,它看起来像这样(取决于页面上的坐标数量):
584|521,590|519,594|513,594|513,590|517,594|513,592|517,590|517,594|513,590|519,,
我的目标是,对于每个坐标,它会保存页面上发生坐标的次数。我似乎无法弄清楚如何这样做,所以任何帮助都会非常感激。
由于
答案 0 :(得分:1)
你可以像这样使用正则表达式
"124682895579215".match(/2/g).length;
它会给你表达式的计数
所以你可以在迭代时选择说第一个坐标584然后你可以使用正则表达式检查计数
以及其他信息
您可以使用indexOf检查字符串是否存在
答案 1 :(得分:0)
使用.indexOf()
方法并在每次不返回-1时进行计数,并在每次增量时将前一个索引值+1作为新的起始参数传递。
答案 2 :(得分:0)
您可以使用split
方法。
string.split('517,594').length-1
会返回2
(其中字符串为'584 | 521,590 | 519,594 | 513,594 | 513,590 | 517,594 | 513,592 | 517,590 | 517,594 | 513,590 | 519')
答案 3 :(得分:0)
我不会把它作为字符串来处理。就像,表,是一个数组数组和那些你正在寻找的字符串,实际上是坐标。 Soooo ...... I made a fiddle,但让我们先看一下代码。
// Let's have a type for the coordinates
function Coords(x, y) {
this.x = parseInt(x);
this.y = parseInt(y);
return this;
}
// So that we can extend the type as we need
Coords.prototype.CountMatches = function(arr){
// Counts how many times the given Coordinates occur in the given array
var count = 0;
for(var i = 0; i < arr.length; i++){
if (this.x === arr[i].x && this.y === arr[i].y) count++;
}
return count;
};
// Also, since we decided to handle coordinates
// let's have a method to convert a string to Coords.
String.prototype.ToCoords = function () {
var matches = this.match(/[(]{1}(\d+)[|]{1}(\d+)[)]{1}/);
var nums = [];
for (var i = 1; i < matches.length; i++) {
nums.push(matches[i]);
}
return new Coords(nums[0], nums[1]);
};
// Now that we have our types set, let's have an array to store all the coords
var allCoords = [];
// And some fake data for the 'table'
var rows = [
{ td: '04.shovel (633|455) C46' },
{ td: 'Fruits kata misdragingen (590|519)' },
{ td: 'monster magnet (665|506) C56' },
{ td: 'slayer (660|496) C46' },
{ td: 'Fruits kata misdragingen (590|517)' }
];
// Just like you did, we loop through the 'table'
for (var i = 0; i < rows.length; i++) {
var td = rows[i].td; //<-this would be your td text content
// Once we get the string from first td, we use String.prototype.ToCoords
// to convert it to type Coords
allCoords.push(td.ToCoords());
}
// Now we have all the data set up, so let's have one test coordinate
var testCoords = new Coords(660, 496);
// And we use the Coords.prototype.CountMatches on the allCoords array to get the count
var count = testCoords.CountMatches(allCoords);
// count = 1, since slayer is in there