分析整数的字符串,包括正数和负数,Javascript
因此,我正在研究d3中的标记云示例 当Div悬停在每个单词的上方时,我试图将其定位到每个单词的顶部,但我基本上遇到了一个问题,因为放置Div的方式取决于svg单词元素的transform属性 这个transform属性是我需要解析的字符串,但是该字符串包含我需要获取的正值和负值分析整数的字符串,包括正数和负数,Javascript,javascript,parsing,tags,position,d3.js,Javascript,Parsing,Tags,Position,D3.js,因此,我正在研究d3中的标记云示例 当Div悬停在每个单词的上方时,我试图将其定位到每个单词的顶部,但我基本上遇到了一个问题,因为放置Div的方式取决于svg单词元素的transform属性 这个transform属性是我需要解析的字符串,但是该字符串包含我需要获取的正值和负值 tagCloudHover.style("top", function(){ //parses the words attributes for its position, and gives that
tagCloudHover.style("top", function(){
//parses the words attributes for its position, and gives that position to tagCloudHover
var str, matches, index, num;
str = thisWord.attr("transform");
matches = str.match(/\d+/g);
for (index = 1; index < 2; ++index) {
num = (parseInt(matches[index], 10));
}
if(num<0){
return -num+"px";
}else{
return num+"px";
}
});
tagCloudHover.style(“top”,function(){
//解析单词属性的位置,并将该位置提供给tagCloudHover
var str,matches,index,num;
str=thisWord.attr(“转换”);
matches=str.match(/\d+/g);
对于(索引=1;索引<2;++索引){
num=(parseInt(匹配[index],10));
}
如果(num您的正则表达式应该是/-?\d+/g
,基本上是在模式中添加“可选的-
”。如果您知道需要解析哪些值,您可以将负的值乘以-1
例如:
num = -1 * (parseInt(matches[index], 10));
你想用for
循环做什么?它只会有一次迭代。而且,考虑到你最后的if
语句似乎是取一个负数,然后把它变成一个正数,为什么不保留当前的正则表达式,只抓住数字,省略if/else?伙计,如果答案就在前面,我讨厌/喜欢它我的全部时间!失败时:签名空间digit@MichałWereda这首先是无效的输入。